-
Notifications
You must be signed in to change notification settings - Fork 0
/
NormalBFS.java
84 lines (77 loc) · 2.3 KB
/
NormalBFS.java
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/** https://www.hackerrank.com/challenges/bfsshortreach/problem #bfs #shortest-path */
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;
public class NormalBFS {
static void BFS(
int startNode,
ArrayList<ArrayList<Integer>> graph,
ArrayList<Integer> path,
ArrayList<Boolean> visited) {
Deque<Integer> queue = new LinkedList<Integer>();
queue.addLast(startNode);
visited.set(startNode, true);
while (!queue.isEmpty()) {
int node = queue.pollFirst();
for (int i : graph.get(node)) {
if (visited.get(i) == false) {
path.set(i, node);
visited.set(i, true);
queue.addLast(i);
}
}
}
}
static int getVisitedNode(int s, int f, ArrayList<Integer> path) {
if (s == f) {
return 0;
}
if (path.get(f) == -1) {
return 0;
} else {
return 1 + getVisitedNode(s, path.get(f), path);
}
}
static String getResult(int startNode, int targetNode, ArrayList<Integer> path) {
String rs = "";
if (startNode != targetNode) {
int temp = getVisitedNode(startNode, targetNode, path);
rs = String.valueOf((temp != 0) ? (temp * 6) : -1) + " ";
}
return rs;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int q = sc.nextInt();
ArrayList<String> rt = new ArrayList<>();
for (int k = 0; k < q; k++) {
int n = sc.nextInt();
int m = sc.nextInt();
ArrayList<Integer> path = new ArrayList<>(n + 1);
ArrayList<Boolean> visited = new ArrayList<>(n + 1);
ArrayList<ArrayList<Integer>> graph = new ArrayList<ArrayList<Integer>>(n + 1);
for (int i = 0; i < n + 1; ++i) {
graph.add(new ArrayList<Integer>());
path.add(-1);
visited.add(false);
}
for (int i = 0; i < m; ++i) {
int u = sc.nextInt();
int v = sc.nextInt();
graph.get(u).add(v);
graph.get(v).add(u);
}
int startNode = sc.nextInt();
BFS(startNode, graph, path, visited);
StringBuilder sb = new StringBuilder();
for (int i = 1; i < n + 1; ++i) {
sb.append(getResult(startNode, i, path));
}
rt.add(sb.toString());
}
for (String s : rt) {
System.out.println(s);
}
}
}