1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | import java.util.ArrayList; import java.util.Scanner; import java.io.FileInputStream; class Solution { static int n; static int[][] adj; static int[] visited; static ArrayList<Integer> queue; public static void main(String args[]) throws Exception { // Scanner sc = new Scanner(new FileInputStream("sample_input.txt")); Scanner sc = new Scanner(System.in); n = sc.nextInt(); int input1 = sc.nextInt() - 1; int input2 = sc.nextInt() - 1; int m = sc.nextInt(); adj = new int[n][n]; visited = new int[n]; queue = new ArrayList<Integer>(); for (int i = 0; i < m; i++) { int parent = sc.nextInt() - 1; int child = sc.nextInt() - 1; adj[parent][child] = 1; adj[child][parent] = 1; } BFS(input1, input2); if (visited[input2] == 0) System.out.println("-1"); } // main static void BFS(int input1, int input2) { int level = 0; visited[input1] = 1; queue.add(input1); while (queue.isEmpty() != true) { int queue_size = queue.size(); for (int i = 0; i < queue_size; i++) { int curr = queue.get(0); queue.remove(0); for (int j = 0; j < n; j++) { if (adj[curr][j] == 1 && visited[j] == 0) { visited[j] = 1; queue.add(j); if (j == input2) { System.out.println(level + 1); } } } } // queue_size for level++; } // while } // BFS } | cs |
'공부 > 알고리즘문제' 카테고리의 다른 글
백준 7562 나이트의 이동 (0) | 2017.04.15 |
---|---|
백준 2178 미로 탐색 (0) | 2017.04.15 |
백준 1260 DFS와 BFS (0) | 2017.04.15 |
백준 1012 유기농 배추 (0) | 2017.04.13 |
백준 13458 시험 감독 (0) | 2017.04.12 |