Skip to content

Commit 853386f

Browse files
authored
use set to keep track of visited nodes, corresponding adjustments to doctest
1 parent 692c0dc commit 853386f

File tree

1 file changed

+6
-6
lines changed

1 file changed

+6
-6
lines changed

Graphs/BreadthFirstSearch.js

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,17 @@ Breadth-first search is an algorithm for traversing a graph. It's discovers all
66

77
/*
88
Doctests
9-
> breadthFirstSearch(graph, "C")
9+
> Array.from(breadthFirstSearch(graph, "C"))
1010
[ 'C', 'D', 'A', 'B', 'E' ]
11-
> breadthFirstSearch(graph, "A")
11+
> Array.from(breadthFirstSearch(graph, "A"))
1212
[ 'A', 'B', 'D', 'E' ]
13-
> breadthFirstSearch(graph, "F")
13+
> Array.from(breadthFirstSearch(graph, "F"))
1414
[ 'F', 'G' ]
1515
*/
1616

1717
function breadthFirstSearch (graph, startingNode) {
1818
// visited keeps track of all nodes visited
19-
const visited = []
19+
const visited = new Set()
2020

2121
// queue contains the nodes to be explored in the future
2222
const queue = [startingNode]
@@ -25,9 +25,9 @@ function breadthFirstSearch (graph, startingNode) {
2525
// start with the queue's first node
2626
const node = queue.shift()
2727

28-
if (!visited.includes(node)) {
28+
if (!visited.has(node)) {
2929
// mark the node as visited
30-
visited.push(node)
30+
visited.add(node)
3131
const neighbors = graph[node]
3232

3333
// put all its neighbors into the queue

0 commit comments

Comments
 (0)