35 lines
761 B
JavaScript
35 lines
761 B
JavaScript
|
// https://www.freecodecamp.org/learn/coding-interview-prep/data-structures/breadth-first-search
|
||
|
|
||
|
function bfs(graph, root) {
|
||
|
const nodesLen = {};
|
||
|
const n_nodes = graph[root].length;
|
||
|
for (let dst = 0; dst < n_nodes; dst++) {
|
||
|
nodesLen[dst] = Infinity;
|
||
|
}
|
||
|
nodesLen[root] = 0;
|
||
|
for (let q = [root], d = 1; ; d++) {
|
||
|
const newQ = [];
|
||
|
for (let src of q) {
|
||
|
for (let dst = 0; dst < n_nodes; dst++) {
|
||
|
if (nodesLen[dst] > d && graph[src][dst] > 0) {
|
||
|
nodesLen[dst] = d;
|
||
|
newQ.push(dst);
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
if (newQ.length <= 0) {
|
||
|
break;
|
||
|
}
|
||
|
q = newQ;
|
||
|
}
|
||
|
return nodesLen;
|
||
|
}
|
||
|
|
||
|
var exBFSGraph = [
|
||
|
[0, 1, 0, 0],
|
||
|
[1, 0, 1, 0],
|
||
|
[0, 1, 0, 1],
|
||
|
[0, 0, 1, 0],
|
||
|
];
|
||
|
console.log(bfs(exBFSGraph, 3));
|