Standard BFS
Use a queue and visited set to traverse level by level.
function bfsOfGraph(adj) {
const visited = new Set([0]), q = [0], result = [];
let head = 0;
while (head < q.length) {
const node = q[head++];
result.push(node);
for (const next of adj[node]) {
if (!visited.has(next)) { visited.add(next); q.push(next); }
}
}
return result;
}Time: O(V + E) | Space: O(V)
Loading discussion…
Saved in this browser only. Private to you.