BFS of graph | Practice
Given a directed graph represented as an adjacency list, return the BFS traversal starting from node 0.
Example: adj = [[1,2],[3],[4],[],[]] → Output: [0,1,2,3,4]
Sample Input
—
Sample Output
—
Constraints
- 1 <= V, E <= 10^4
Test Cases
Case 1
Args: [[[1,2],[3],[4],[],[]]]
Expected: [0,1,2,3,4]
Standard BFS
Use a queue and visited set to traverse level by level.
function bfsOfGraph(adj) {
const visited = new Set([0]), q = [0], result = [];
while (q.length) {
const node = q.shift();
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)
Saved in this browser only. Private to you.