freeCodeCamp/Data Structures/bfs.js

35 lines
761 B
JavaScript
Raw Permalink Normal View History

2023-09-15 08:25:19 +02:00
// 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));