Search for a command to run...
Explore a graph level by level with a queue
Graph playground
Edit undirected edges and replay the algorithm from a new start node.
Initialize the BFS queue
Start at node 0 and place it in the queue.
Breadth-First Search
1function bfs(graph, start) {2 const queue = [start];3 const visited = new Set([start]);//start: 0queue: [0]visited: [0]4 5 while (queue.length > 0) {6 const current = queue.shift();7 for (const neighbor of graph[current]) {8 if (!visited.has(neighbor)) {9 visited.add(neighbor);10 queue.push(neighbor);11 }12 }13 }14}