-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBFS.java
More file actions
44 lines (38 loc) · 1.19 KB
/
BFS.java
File metadata and controls
44 lines (38 loc) · 1.19 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
//BFS on a graph, this program doesn't really do anything
import java.util.*;
import java.io.*;
public class BFS {
public static void main(String[] args) throws IOException {
FastScanner in = new FastScanner(System.in);
PrintWriter out = new PrintWriter(System.out);
int n = in.nextInt();
int m = in.nextInt();
ArrayList<Integer>[] adj = new ArrayList[n + 1];
boolean[] vis = new boolean[n + 1];
Arrays.setAll(adj, x -> new ArrayList<>());
for (int i = 0; i < m; i++) {
int u = in.nextInt();
int v = in.nextInt();
adj[u].add(v);
adj[v].add(u);
}
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
bfs(adj, vis, i);
}
}
}
static void bfs(ArrayList<Integer>[] adj, boolean[] vis, int node) {
ArrayDeque<Integer> nodeQ = new ArrayDeque<>();
nodeQ.add(node);
while (nodeQ.size() > 0) {
int cur = nodeQ.poll();
for (int to : adj[cur]) {
if (!vis[to]) {
vis[to] = true;
nodeQ.add(to);
}
}
}
}
}