Skip to content

Commit 40a4caf

Browse files
committed
Implement BFS for Graph class
1 parent c2b6122 commit 40a4caf

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed

Graph.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,21 @@ class Graph {
5353
}
5454
return Array.from(visited);
5555
}
56+
BFS(start) {
57+
if (!this.adjacencyList[start]) return [];
58+
59+
const queue = [start];
60+
const visited = new Set();
61+
62+
while (queue.length) {
63+
let current = queue.shift();
64+
visited.add(current);
65+
let children = this.adjacencyList[current];
66+
for (let child of children) {
67+
if (!visited.has(child)) queue.push(child);
68+
}
69+
}
70+
71+
return Array.from(visited);
72+
}
5673
}

0 commit comments

Comments
 (0)