Skip to content

Commit ca78e8d

Browse files
sPredictorX1708#42: implemented BFS with the same format of DFS
1 parent 7c086cc commit ca78e8d

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

Algorithms/BreadthFirstSearch.java

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import java.util.Iterator;
2+
import java.util.LinkedList;
3+
import java.util.Queue;
4+
5+
public class BreadthFirstSearch {
6+
public static void main(String args[])
7+
{
8+
Graph g = new Graph(4);
9+
10+
g.addEdge(0, 1);
11+
g.addEdge(0, 2);
12+
g.addEdge(1, 2);
13+
g.addEdge(2, 0);
14+
g.addEdge(2, 3);
15+
g.addEdge(3, 3);
16+
17+
g.BFS(2);
18+
}
19+
}
20+
21+
22+
class Graph {
23+
private int numVertices;
24+
private LinkedList<Integer> adj[];
25+
private boolean[] visited;
26+
private Queue<Integer> queue;
27+
28+
public Graph(int vertices) {
29+
numVertices = vertices;
30+
adj = new LinkedList[vertices];
31+
visited = new boolean[vertices];
32+
queue = new LinkedList<>();
33+
34+
for (int i = 0; i < vertices; i++)
35+
adj[i] = new LinkedList<Integer>();
36+
}
37+
38+
void addEdge(int src, int dest) {
39+
adj[src].add(dest);
40+
}
41+
42+
void BFS(int vertex) {
43+
queue.clear();
44+
queue.add(vertex);
45+
visited[vertex] = true;
46+
while(!queue.isEmpty()) {
47+
vertex = queue.poll();
48+
System.out.print(vertex + " ");
49+
Iterator ite = adj[vertex].listIterator();
50+
while (ite.hasNext()) {
51+
int adj = (int) ite.next();
52+
if (!visited[adj]) {
53+
visited[adj] = true;
54+
queue.add(adj);
55+
}
56+
}
57+
}
58+
}
59+
}

0 commit comments

Comments
 (0)