Last active
May 15, 2020 04:35
-
-
Save trykhov/07bb1d4ca4de987155e27a211e921084 to your computer and use it in GitHub Desktop.
BFS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// assuming that the input is an adjacency list | |
// e.g adj = {A:[B,C,D], B:[E,F], ... } | |
function bfs(adj, s, t) { | |
// adj is the adjacency list | |
// s is the starting vertex | |
// t is the final destination | |
// initialize the queue | |
let queue = []; | |
// add s to the queue | |
queue.push(s); | |
// mark s as visited so it won't be added again | |
s.visited = true; | |
while(queue.length > 0) { | |
// pop the first element of the queue | |
let v = queue.shift(); | |
// adj[v] represents the neighbors of v | |
for(let neighbor of adj[v]) { | |
// if the neighbor isn't visited | |
if(!neighbor.visited) { | |
// add the unvisited neighbor to the queue | |
queue.push(neighbor); | |
// mark the vertex as visited | |
neighbor.visited = true; | |
// if the neighbor is the destination, we have reached the destination | |
if(neighbor == t) return true; | |
}; | |
} | |
} | |
// if the destination isn't reached, then the destination can't be reached from s | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment