내 코드
package com.company;
import java.io.*;
import java.util.*;
public class Main {
static int a, b, N, M;
static int count = 0;
static boolean[] visited;
static ArrayList<ArrayList<Integer>> list = new ArrayList<>();
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
a = Integer.parseInt(st.nextToken());
b = Integer.parseInt(st.nextToken());
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
visited = new boolean[N + 1];
for (int i = 0; i <= N; i++) {
list.add(new ArrayList<>());
}
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int x1 = Integer.parseInt(st.nextToken());
int x2 = Integer.parseInt(st.nextToken());
list.get(x1).add(x2);
list.get(x2).add(x1);
}
Queue<Node> pq = new PriorityQueue<>();
pq.add(new Node(a, 0));
while (!pq.isEmpty()) {
Node x = pq.poll();
if (visited[x.num])
continue;
visited[x.num] = true;
if (x.num == b) {
System.out.println(x.count);
return;
}
for (int i : list.get(x.num)) {
if (!visited[i])
pq.add(new Node(i, x.count + 1));
}
}
System.out.println(-1);
}
}
class Node implements Comparable<Node> {
int num, count;
public Node(int num, int count) {
this.num = num;
this.count = count;
}
@Override
public int compareTo(Node o) {
return this.count - o.count;
}
}
'코딩테스트 > [백준] 코딩테스트 연습' 카테고리의 다른 글
소수 화폐 (0) | 2021.12.29 |
---|---|
줄세우기 - 2631번 (0) | 2021.12.28 |
악덕 영주 혜유 (0) | 2021.12.24 |
플로이드 - 11404번 (0) | 2021.12.24 |
쉬운 계단 수 - 10844번 (0) | 2021.12.03 |