11403번: 경로 찾기

가중치 없는 방향 그래프 G가 주어졌을 때, 모든 정점 (i, j)에 대해서, i에서 j로 가는 경로가 있는지 없는지 구하는 프로그램을 작성하시오.

www.acmicpc.net

 

 

 

 


 

 

 

 

  • 풀이

 

문제는 그래프 (i,j)에서 i에서 j로 가는 경로가 있는지 없는지 구해주는 문제입니다.

 

문제를 읽자마자 가장 먼저 생각난 알고리즘은 플로이드와샬이였습니다.

 

왜? 플로이드와샬이 바로 생각났는지에 대해 궁금해 하시는 분들이 있을 수 있을 것 같아 간단하게 설명을 드리자면 플로이드 와샬의 목적에 대해서 생각해볼 필요가 있습니다.

 

플로이드와샬의 목적은 모든 정점에서 모든 정점으로의 최단경로를 찾는 것 입니다. 플로이드의 기본 코드를 보면 k인덱스를 기준으로 i에서 j로 가는 가장 작은 가중치를 초기화 시켜줍니다. 

플로이드의 초기화 기본 코드는 array[i][j] = Math.min(array[i][j], array[i][k]+array[k][j])입니다. 현재 초기화된 값보다 i에서 k로 가는 경로와 k에서 j로 가는 경로의 값을 더한 값이 더 작다면 값을 초기화 시켜준다는 것 입니다.

 

이를 이어서 생각하면 array[i][k] + array[k][j]의 값이 2인 경우 i->k로 가는 경우도 있고 k->j로 가는 경우도 있다는 것을 의미합니다. 따라서 현재 array[i][j]값이 1이 아니여도 array[i][k]로 가는 경로가 있고 array[k][j]로 가는 경우가 있다면 array[i][j]를 갈 수 있다를 토대로 코드를 작성했습니다.

 

 

  • 코드

 

 

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

public class Main {
	static int N;
	static int[][] array;
	static StringBuilder sb;
	
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		SetData();
		System.out.println(sb);
	}
	
	private static void SetData() throws Exception {
		InputReader in = new InputReader(System.in);
		
		N = in.nextInt();
		sb = new StringBuilder();
		array = new int[N][N];
		
		for(int i = 0; i < N; i++) {
			for(int j = 0; j < N; j++) {
				array[i][j] = in.nextInt();
			}
		}
		
		for(int k = 0; k < N; k++) {
			for(int i = 0; i < N; i++) {
				for(int j = 0; j < N; j++) {
					// j까지 도달한다면
					if(array[i][k] + array[k][j] == 2) {
						array[i][j] = 1;
					}
				}
			}
		}
		
		for(int i = 0; i < N; i++) {
			for(int j = 0; j < N; j++) {
				sb.append(array[i][j] + " ");
			}
			sb.append("\n");
		}
	}
}

class InputReader {
	private final InputStream stream;
	private final byte[] buf = new byte[8192];
	private int curChar, snumChars;

	public InputReader(InputStream st) {
		this.stream = st;
	}

	public int read() {
		if (snumChars == -1)
			throw new InputMismatchException();
		if (curChar >= snumChars) {
			curChar = 0;
			try {
				snumChars = stream.read(buf);
			} catch (IOException e) {
				throw new InputMismatchException();
			}
			if (snumChars <= 0)
				return -1;
		}
		return buf[curChar++];
	}

	public int nextInt() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		int res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public long nextLong() {
		int c = read();
		while (isSpaceChar(c)) {
			c = read();
		}
		int sgn = 1;
		if (c == '-') {
			sgn = -1;
			c = read();
		}
		long res = 0;
		do {
			res *= 10;
			res += c - '0';
			c = read();
		} while (!isSpaceChar(c));
		return res * sgn;
	}

	public int[] nextIntArray(int n) {
		int a[] = new int[n];
		for (int i = 0; i < n; i++) {
			a[i] = nextInt();
		}
		return a;
	}

	public String nextLine() {
		int c = read();
		while (isSpaceChar(c))
			c = read();
		StringBuilder res = new StringBuilder();
		do {
			res.appendCodePoint(c);
			c = read();
		} while (!isEndOfLine(c));
		return res.toString();
	}

	public boolean isSpaceChar(int c) {
		return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
	}

	private boolean isEndOfLine(int c) {
		return c == '\n' || c == '\r' || c == -1;
	}
}

+ Recent posts