JSFiddle - React, Tailwind, and code Playground
JavaScript
console.clear();
let c = (...s) => console.log(...s);
// Graph - BFS
// output - an object { <node> : <distance from startNode> }
function BFS(graph, startNode) {
let distances = {};
// default distance from startNode to other nodes is Infinity
for (let i = 0; i < graph.length; i++) {
distances[i] = Infinity;
}
distances[startNode] = 0; // startNode to startNode is 0
let queue = [startNode];
let current;
// tranverse queue
while (queue.length > 0) {
current = queue.shift();
let connectedToCurrent = graph[current];
let neighbours = []; // list of nodes connected to current
let index = connectedToCurrent.indexOf(1); // get index of first connected node ie value = 1
while (index != -1) {
neighbours.push(index);
index = connectedToCurrent.indexOf(1, index + 1);
}
// most complicated part
for (let i = 0; i < neighbours.length; i++) {
if (distances[neighbours[i]] == Infinity) {
distances[neighbours[i]] = distances[current] + 1;
queue.push(neighbours[i]);
}
}
}
return distances;
}
// https://imgur.com/npQHyTd
let graph = [
[0, 1, 1, 1, 0], // node 0
[0, 0, 1, 0, 0],
[1, 1, 0, 0, 0],
[0, 0, 0, 1, 0],
[0, 1, 0, 0, 0],
]
let startNode = 1;
c(BFS(graph, startNode));