Created
May 22, 2021 04:18
-
-
Save S-codes14/aea2c5e4a8f9f0d7ce09bcab83e30fd8 to your computer and use it in GitHub Desktop.
Graphs: breadth-first search
This file contains hidden or 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
/* Graphs: Breadth-first search */ | |
function bfs(graph, root) { | |
var nodesLen = {}; | |
for (var i = 0; i < graph.length; i++) { | |
nodesLen[i] = Infinity; | |
} | |
nodesLen[root] = 0; | |
var queue = [root]; | |
var current; | |
while (queue.length != 0) { | |
current = queue.shift(); | |
var curConnected = graph[current]; | |
var neighborIdx = []; | |
var idx = curConnected.indexOf(1); | |
while (idx != -1) { | |
neighborIdx.push(idx); | |
idx = curConnected.indexOf(1, idx + 1); | |
} | |
for (var j = 0; j < neighborIdx.length; j++) { | |
if (nodesLen[neighborIdx[j]] == Infinity) { | |
nodesLen[neighborIdx[j]] = nodesLen[current] + 1; | |
queue.push(neighborIdx[j]); | |
} | |
} | |
} | |
return nodesLen; | |
}; | |
var exBFSGraph = [ | |
[0, 1, 1, 1, 0], | |
[0, 0, 1, 0, 0], | |
[1, 1, 0, 0, 0], | |
[0, 0, 0, 1, 0], | |
[0, 1, 0, 0, 0] | |
]; | |
console.log(bfs(exBFSGraph, 1)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment