-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortestRoutGraph.java
More file actions
54 lines (48 loc) · 1.49 KB
/
Copy pathShortestRoutGraph.java
File metadata and controls
54 lines (48 loc) · 1.49 KB
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
import java.util.*;
public class ShortestRoutGraph {
static int[] check;
static int[] dis;
static int n;
static List<ArrayList<Integer>> graph;
static Queue<Integer> queue;
public void solution(int i, int[] check) {
queue = new LinkedList<>();
queue.offer(i);
while (!queue.isEmpty()) {
int size = queue.size();
for (int j = 0; j < size; j++) {
Integer poll = queue.poll();
for (Integer integer : graph.get(poll)) {
if (check[integer] == 0) {
check[integer] = 1;
queue.offer(integer);
dis[integer] = dis[poll] + 1;
}
}
}
}
}
public static void main(String[] args) {
ShortestRoutGraph t = new ShortestRoutGraph();
Scanner scanner = new Scanner(System.in);
n = scanner.nextInt();
int m = scanner.nextInt();
graph = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i <= n; i++) {
graph.add(new ArrayList<>());
}
check = new int[n + 1];
dis = new int[n + 1];
for (int i = 0; i < m; i++) {
int x = scanner.nextInt();
int y = scanner.nextInt();
graph.get(x).add(y);
}
check[1] = 1;
dis[1] = 0;
t.solution(1, check);
for (int di : dis) {
System.out.print(di + " ");
}
}
}