forked from AllAlgorithms/javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbfs.js
More file actions
44 lines (37 loc) · 919 Bytes
/
bfs.js
File metadata and controls
44 lines (37 loc) · 919 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
A non-recursive implementation of bfs with worst-case space complexity O(|E|)
*/
function Vertex (name, neighbours) {
this.name = name;
this.neighbours = neighbours;
}
function bfs (root) {
var visited = {}
var stack = []
stack.push(root)
while(!!stack.length) {
var vertex = stack.shift()
if (!visited[vertex.name]) {
visited[vertex.name] = true
console.log('Visiting vertex ', vertex.name)
var len = vertex.neighbours.length
for (var index = 0; index < len; index++) {
stack.push(vertex.neighbours[index])
}
}
}
}
var root = new Vertex('root', [
new Vertex('child 1', [
new Vertex('grandchild 1', []), new Vertex('grandchild 2', [])
]),
new Vertex('child 2', [
new Vertex('grandchild 3', []),
]),
new Vertex('child 3', [
new Vertex('grandchild 4', [
new Vertex('grandgrandchild 1', [])
]),
]),
])
bfs(root)