Skip to content

Commit f7f8d80

Browse files
committed
bfs algorithm added
1 parent d09134a commit f7f8d80

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

Data-Structure/Graph/bfs.js

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
'use strict';
2+
class Graph {
3+
constructor(vertex) {
4+
this.listArray = new Array(vertex + 1);
5+
this.visitedArr = new Array(vertex + 1);
6+
for (let index = 0; index <= vertex; index++) {
7+
this.listArray[index] = [];
8+
this.visitedArr[index] = 0;
9+
}
10+
}
11+
addEdge(v, u) {
12+
this.listArray[v].push(u);
13+
}
14+
15+
bfs(startVertex) {
16+
let queue = [startVertex];
17+
this.visitedArr[startVertex] = 1;
18+
let bfsResult = '';
19+
while (queue.length != 0) {
20+
let temp = queue.shift();
21+
bfsResult = bfsResult + temp + ' ';
22+
let tList = this.listArray[temp];
23+
for (let index = 0; index < tList.length; index++) {
24+
if (!this.visitedArr[tList[index]]) {
25+
this.visitedArr[tList[index]] = 1;
26+
queue.push(tList[index]);
27+
}
28+
}
29+
}
30+
console.log('BFS ->', bfsResult);
31+
}
32+
}
33+
34+
let g1 = new Graph(7);
35+
g1.addEdge(1, 2);
36+
g1.addEdge(1, 3);
37+
g1.addEdge(1, 5);
38+
39+
g1.addEdge(2, 1);
40+
g1.addEdge(2, 4);
41+
g1.addEdge(2, 7);
42+
43+
g1.addEdge(3, 1);
44+
g1.addEdge(3, 6);
45+
46+
g1.addEdge(5, 1);
47+
g1.addEdge(5, 6);
48+
49+
g1.addEdge(6, 3);
50+
g1.addEdge(6, 5);
51+
g1.bfs(1);

0 commit comments

Comments
 (0)