-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBfsAlgorithm.java
More file actions
57 lines (51 loc) · 1.64 KB
/
Copy pathBfsAlgorithm.java
File metadata and controls
57 lines (51 loc) · 1.64 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
import java.util.*;
class BfsAlgorithm {
public static void main(String[] args) {
int n = 15;
List<Edge> nodes = Arrays.asList(new Edge(1, 2), new Edge(1, 3), new Edge(1, 4), new Edge(2, 5), new Edge(2, 6), new Edge(4, 7), new Edge(4, 8), new Edge(5, 9), new Edge(5, 10), new Edge(7, 12), new Edge(7, 12));
Graph graph = new Graph(nodes, n);
boolean[] visitors = new boolean[n];
Queue<Integer> q = new ArrayDeque<>();
for (int i = 0; i < n; i++) {
if (!visitors[i]) {
visitors[i] = true;
q.add(i);
bfsImplementation(graph, q, visitors);
}
}
}
private static void bfsImplementation(Graph graph, Queue<Integer> q, boolean[] visitors) {
if (q.isEmpty()) return;
int nodeIndex = q.poll();
System.out.print(nodeIndex + " ");
for (int node : graph.adjList.get(nodeIndex)) {
if (!visitors[node]) {
visitors[node] = true;
q.add(node);
}
}
bfsImplementation(graph, q, visitors);
}
}
class Edge {
int src, dest;
public Edge(int src, int dest) {
this.src = src;
this.dest = dest;
}
}
class Graph {
List<List<Integer>> adjList;
public Graph(List<Edge> nodes, int n) {
this.adjList = new ArrayList<>();
for (int i = 0; i < n; i++) {
adjList.add(new ArrayList<>());
}
for (Edge node : nodes) {
int src = node.src;
int dest = node.dest;
adjList.get(src).add(dest);
adjList.get(dest).add(src);
}
}
}