Skip to content

Commit 7466a7f

Browse files
Merge pull request fnplus#62 from EkinEren/imp/add-bfs-graph-algorithm
Thanks for contributing
2 parents 2244a60 + bbb17e4 commit 7466a7f

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed
Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
/* Java implementation of BFS algorithm to traverse a graph.
2+
*
3+
* Starting from the root node, this algorithm explores all the neighboring nodes
4+
* and keeps track of visited nodes to make sure no node is visited more than once. */
5+
6+
import java.util.Iterator;
7+
import java.util.LinkedList;
8+
9+
public class BreadthFirstSearch {
10+
11+
/* Number of vertices */
12+
private int V;
13+
/*Adjacency Lists */
14+
private LinkedList<Integer> adj[];
15+
16+
BreadthFirstSearch(int v)
17+
{
18+
V = v;
19+
adj = new LinkedList[v];
20+
for (int i = 0; i < v; ++i)
21+
adj[i] = new LinkedList();
22+
}
23+
24+
/* Add an edge to the graph. Node w is adjacent to given Node v */
25+
void addEdge(int v,int w)
26+
{
27+
adj[v].add(w);
28+
}
29+
30+
/* BFS algorithm which starts from a given node, s */
31+
void BFS(int s)
32+
{
33+
/* List of visited vertices; all false in the beginning) */
34+
boolean visited[] = new boolean[V];
35+
36+
/* Queue data structure is used for BFS */
37+
LinkedList<Integer> queue = new LinkedList<>();
38+
39+
/* Mark starting node s as visited and enqueue it */
40+
visited[s]=true;
41+
queue.add(s);
42+
43+
/* Until queue is empty, dequeue a single node in queue and look for it's neighboring vertices.
44+
* If an adjecent node hasn't been visited yet, set it as visited and enqueue this node. s*/
45+
while (queue.size() != 0)
46+
{
47+
/* Dequeue */
48+
s = queue.poll();
49+
System.out.print( s + " ");
50+
51+
/* Get all adjacent vertices */
52+
Iterator<Integer> i = adj[s].listIterator();
53+
while (i.hasNext())
54+
{
55+
int n = i.next();
56+
if (!visited[n])
57+
{
58+
visited[n] = true;
59+
queue.add(n);
60+
}
61+
}
62+
}
63+
}
64+
65+
public static void main(String[] args) {
66+
67+
/* Create Graph with 4 vertices */
68+
BreadthFirstSearch g = new BreadthFirstSearch(4);
69+
70+
/* Add edges in graph */
71+
g.addEdge(0, 0);
72+
g.addEdge(0,1);
73+
g.addEdge(0, 2);
74+
g.addEdge(1, 2);
75+
g.addEdge(2, 0);
76+
g.addEdge(2, 3);
77+
78+
System.out.println("Traverse graph with BFS...");
79+
System.out.println("Starting Vertex: 2");
80+
81+
g.BFS(2);
82+
}
83+
}

0 commit comments

Comments
 (0)