From 853386fa97535c09edce4640be2399f6f0da06a7 Mon Sep 17 00:00:00 2001 From: algobytewise Date: Sat, 27 Feb 2021 09:44:33 +0530 Subject: [PATCH] use set to keep track of visited nodes, corresponding adjustments to doctest --- Graphs/BreadthFirstSearch.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/Graphs/BreadthFirstSearch.js b/Graphs/BreadthFirstSearch.js index a342cb5a9..7546fd853 100644 --- a/Graphs/BreadthFirstSearch.js +++ b/Graphs/BreadthFirstSearch.js @@ -6,17 +6,17 @@ Breadth-first search is an algorithm for traversing a graph. It's discovers all /* Doctests -> breadthFirstSearch(graph, "C") +> Array.from(breadthFirstSearch(graph, "C")) [ 'C', 'D', 'A', 'B', 'E' ] -> breadthFirstSearch(graph, "A") +> Array.from(breadthFirstSearch(graph, "A")) [ 'A', 'B', 'D', 'E' ] -> breadthFirstSearch(graph, "F") +> Array.from(breadthFirstSearch(graph, "F")) [ 'F', 'G' ] */ function breadthFirstSearch (graph, startingNode) { // visited keeps track of all nodes visited - const visited = [] + const visited = new Set() // queue contains the nodes to be explored in the future const queue = [startingNode] @@ -25,9 +25,9 @@ function breadthFirstSearch (graph, startingNode) { // start with the queue's first node const node = queue.shift() - if (!visited.includes(node)) { + if (!visited.has(node)) { // mark the node as visited - visited.push(node) + visited.add(node) const neighbors = graph[node] // put all its neighbors into the queue