Published
Edited
Dec 16, 2021
Insert cell
# BFS
Insert cell
bfs(6, [
[3, 6],
[4, 3],
[3, 2],
[1, 3],
[1, 2],
[2, 4],
[5, 2]
])
Insert cell
function bfs(n, edge) {
const graph = Array.from(Array(n + 1), () => []);
for (const [src, dest] of edge) {
graph[src].push(dest);
graph[dest].push(src);
}

const distance = Array(n + 1).fill(0);
distance[1] = 1;

// BFS
const queue = [1];
while (queue.length > 0) {
const src = queue.shift();
for (const dest of graph[src]) {
if (distance[dest] === 0) {
queue.push(dest);
distance[dest] = distance[src] + 1;
}
}
}

return {graph, distance}
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more