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
| public class boj_2644 { static List<List<Integer>> graphList; static int[] isCheck; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(br.readLine()); StringTokenizer st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken()); int y = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(br.readLine()); isCheck = new int[n+1]; graphList = new ArrayList<>(); for(int i=0; i<=n; i++){ graphList.add(new ArrayList<>()); }
for(int i=0; i<m; i++){ st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); graphList.get(a).add(b); graphList.get(b).add(a); } dfs(x,y); if(isCheck[y] != 0){ System.out.println(isCheck[y]); }else { System.out.println(-1); } } private static void dfs(int x, int dest){ if(x == dest){ return; } for(int i=0; i<graphList.get(x).size(); i++){ int y = graphList.get(x).get(i); if(isCheck[y] == 0){ isCheck[y] = isCheck[x] + 1; dfs(y,dest); } } }
private static void bfs(int start, int end) { Queue<Integer> q = new LinkedList<>(); q.add(start); isCheck[start] = 0;
while(!q.isEmpty()){ int x = q.poll(); if(x == end){ break; } for(int i=0; i<graphList.get(x).size(); i++){ int y = graphList.get(x).get(i); if(isCheck[y] == 0){ isCheck[y] = isCheck[x] + 1; q.add(y); } } } } }
|