Skip to content

Commit 2e57633

Browse files
authored
Merge pull request #994 from Thanisthani/main
Create BFS algorithm
2 parents 6259062 + 369a40e commit 2e57633

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

BFS algorithm.java

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
2+
import java.io.*;
3+
import java.util.*;
4+
5+
6+
class Graph
7+
{
8+
private int V;
9+
private LinkedList<Integer> adj[];
10+
11+
Graph(int v)
12+
{
13+
V = v;
14+
adj = new LinkedList[v];
15+
for (int i=0; i<v; ++i)
16+
adj[i] = new LinkedList();
17+
}
18+
19+
20+
void addEdge(int v,int w)
21+
{
22+
adj[v].add(w);
23+
}
24+
25+
void BFS(int s)
26+
{
27+
28+
boolean visited[] = new boolean[V];
29+
30+
31+
LinkedList<Integer> queue = new LinkedList<Integer>();
32+
33+
34+
visited[s]=true;
35+
queue.add(s);
36+
37+
while (queue.size() != 0)
38+
{
39+
40+
s = queue.poll();
41+
System.out.print(s+" ");
42+
43+
44+
Iterator<Integer> i = adj[s].listIterator();
45+
while (i.hasNext())
46+
{
47+
int n = i.next();
48+
if (!visited[n])
49+
{
50+
visited[n] = true;
51+
queue.add(n);
52+
}
53+
}
54+
}
55+
}
56+
57+
58+
public static void main(String args[])
59+
{
60+
Graph g = new Graph(4);
61+
62+
g.addEdge(0, 1);
63+
g.addEdge(0, 2);
64+
g.addEdge(1, 2);
65+
g.addEdge(2, 0);
66+
g.addEdge(2, 3);
67+
g.addEdge(3, 3);
68+
69+
System.out.println(" Breadth First Traversal "+
70+
"(starting from vertex 2)");
71+
72+
g.BFS(2);
73+
}
74+
}

0 commit comments

Comments
 (0)