Skip to content

Commit 7eb0a06

Browse files
committed
Add BFS implementation
1 parent cb9a426 commit 7eb0a06

File tree

1 file changed

+73
-0
lines changed
  • src/main/java/com/packt/datastructuresandalg/lesson6/bfs

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
package com.packt.datastructuresandalg.lesson6.bfs;
2+
3+
import java.util.ArrayList;
4+
import java.util.LinkedList;
5+
import java.util.Queue;
6+
7+
public class Graph {
8+
ArrayList<Integer> adj[];
9+
10+
public Graph(int nodes) {
11+
this.adj = new ArrayList[nodes];
12+
for (int i = 0; i < nodes; i++) {
13+
this.adj[i] = new ArrayList<>();
14+
}
15+
}
16+
17+
public void addEdge(int u, int v) {
18+
this.adj[u].add(v);
19+
}
20+
21+
public int[] bfs(int start) {
22+
int[] parent = new int[this.adj.length];
23+
boolean[] visited = new boolean[this.adj.length];
24+
25+
for (int i = 0; i < this.adj.length; i++) {
26+
parent[i] = -1;
27+
visited[i] = false;
28+
}
29+
30+
visited[start] = true;
31+
Queue<Integer> q = new LinkedList<>();
32+
q.add(start);
33+
while (!q.isEmpty()) {
34+
int current = q.remove();
35+
for (int i = 0; i < this.adj[current].size(); i++) {
36+
int next = this.adj[current].get(i);
37+
if (!visited[next]) {
38+
visited[next] = true;
39+
parent[next] = current;
40+
q.add(next);
41+
}
42+
}
43+
}
44+
return parent;
45+
}
46+
47+
public static void main(String [] args) {
48+
Graph g = new Graph(6);
49+
g.addEdge(0, 1);
50+
g.addEdge(0, 3);
51+
g.addEdge(1, 4);
52+
g.addEdge(2, 4);
53+
g.addEdge(2, 5);
54+
g.addEdge(3, 1);
55+
g.addEdge(4, 3);
56+
g.addEdge(5, 5);
57+
int[] parent = g.bfs(2);
58+
for (int i = 0; i < 6; i++) {
59+
System.out.print("Path from 2 to " + i + ":");
60+
if (parent[i] == -1 && i != 2)
61+
System.out.println(" None");
62+
else {
63+
String path = "";
64+
int j = i;
65+
while (j != -1) {
66+
path = (" " + j) + path;
67+
j = parent[j];
68+
}
69+
System.out.println(path);
70+
}
71+
}
72+
}
73+
}

0 commit comments

Comments
 (0)