์ค๋์ ํ์ต ํค์๋
๋ฌธ์ - ๋ฏธ๋ค๋ฌ
์ด์ ๊ณ์ฐ
ํ์ด
import java.util.*;
class Main {
static int n;
static int a, b;
static int m;
static ArrayList<ArrayList<Integer>> list;
static int[] visited;
static void bfs(int start) {
Queue<Integer> q = new LinkedList<>();
q.offer(start);
visited[start] = 0;
while(!q.isEmpty()) {
int x = q.poll();
for(int i = 0; i < list.get(x).size(); i++) {
int y = list.get(x).get(i);
if(visited[y] == -1) { // ๋ฐฉ๋ฌธํ ์ ์ด ์๋ค๋ฉด
visited[y] = visited[x] + 1;
q.offer(y);
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
a = sc.nextInt();
b = sc.nextInt();
m = sc.nextInt();
list = new ArrayList<>();
visited = new int[n + 1];
Arrays.fill(visited, -1);
for(int i = 0; i <= n; i++) {
list.add(new ArrayList<Integer>());
}
for(int i = 0; i < m; i++) {
int x = sc.nextInt();
int y = sc.nextInt();
list.get(x).add(y);
list.get(y).add(x);
}
bfs(a);
System.out.println(visited[b] == -1 ? -1 : visited[b]);
}
}
- BFS๋ฅผ ์ด์ฉํ์ฌ ํ์์ต๋๋ค.
- ์ธ์ ํ ๋
ธ๋ ํ๋๋ฅผ ํ์ํ ๋๋ง๋ค, 1์ด์ฉ ์ฆ๊ฐํด์ค๋๋ค.