forked from Kharda/HackerRank
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfsshortreach.java
More file actions
68 lines (53 loc) · 1.68 KB
/
Copy pathbfsshortreach.java
File metadata and controls
68 lines (53 loc) · 1.68 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int tc = sc.nextInt();
for (int t=0; t<tc; t++) {
int totV = sc.nextInt();
int totE = sc.nextInt();
boolean[] visit = new boolean[totV];
int[] distances = new int[totV];
LinkedList<Integer>[] adjList = new LinkedList[totV];
for (int i=0; i<totV; i++) {
adjList[i] = new LinkedList<Integer>();
}
for (int i=0; i<totV; i++) {
distances[i] = -1;
}
for (int i=0; i< totE; i++) {
int v1 = sc.nextInt()-1;
int v2 = sc.nextInt()-1;
adjList[v1].add(v2);
adjList[v2].add(v1);
}
int start = sc.nextInt()-1;
distances[start] = 0;
Queue<Integer> queue = new LinkedList<Integer>();
queue.add(start);
Integer node = queue.poll();
while (node != null) {
Iterator<Integer> it = adjList[node].iterator();
while (it.hasNext()) {
int nodeVisit = it.next();
if (visit[nodeVisit] == false) {
visit[nodeVisit] = true;
distances[nodeVisit] = distances[node] + 6;
queue.add(nodeVisit);
}
}
node = queue.poll();
}
for (int i=0; i<totV; i++) {
if (i != start) {
System.out.print(distances[i] + " ");
}
}
System.out.println();
}
}
}