[백준] P2644

동민·2021년 3월 11일
import java.util.Scanner;

public class P2644 {
	private static int[][] matrix;
	private static boolean[] visit;
	private static int answer;

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int v = sc.nextInt(), r1 = sc.nextInt(), r2 = sc.nextInt(), e = sc.nextInt();
		matrix = new int[v + 1][v + 1];
		visit = new boolean[v + 1];
		
		for(int i = 1; i <= e; i++) {
			int e1 = sc.nextInt(), e2 = sc.nextInt();
			matrix[e1][e2] = matrix[e2][e1] = 1;
		}
		dfs(r1, r2, 0);
		System.out.println(answer = answer == 0 ? -1 : answer);
		sc.close();
	}
	private static void dfs(int current, int target, int relation) {
		if(current == target) {
			answer = relation;
			return ;
		}
		visit[current] = true;
		for(int i = 1; i < matrix.length; i++) {
			if(matrix[current][i] == 1 && !visit[i]) {
				dfs(i, target, relation + 1);
			}
		}
	}
}
profile
BE Developer

0개의 댓글