-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBFS.java
More file actions
60 lines (48 loc) · 1.54 KB
/
BFS.java
File metadata and controls
60 lines (48 loc) · 1.54 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
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class BFS {
private static ArrayList<ArrayList<Integer>> graph;
private static boolean[] visited;
public static void main(String[] args) {
// Build graph from input
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
graph = new ArrayList<>();
for (int i = 0; i < n; ++i) {
graph.add(new ArrayList<>());
}
visited = new boolean[n];
while (scanner.hasNext()) {
int u = scanner.nextInt();
int v = scanner.nextInt();
graph.get(u).add(v);
}
scanner.close();
// Start BFS from all vertices that aren't visited by then
for (int i = 0; i < n; ++i) {
if (!visited[i]) {
bfs(i);
}
for (boolean isVisited : visited) {
System.out.print(isVisited + " ");
}
System.out.println();
}
}
private static void bfs(int start) {
Queue<Integer> queue = new LinkedList<>();
queue.add(start);
while (!queue.isEmpty()) {
int pos = queue.poll();
visited[pos] = true;
// Add problem-specific logic that should be executed when visiting a vertex here
for (int neighbor : graph.get(pos)) {
if (!visited[neighbor]) {
queue.add(neighbor);
}
}
}
}
}