1. Level-by-Level Set Expansion (Without Queue)
Intuition
Instead of an explicit queue, maintain a list of current level vertices. In each round, collect all unvisited neighbors of the current level into a next level list, marking them visited, until no new vertices are discovered.
Algorithm
- Initialize a visited array of size V to false.
- Set currentLevel = [0] and visited[0] = true.
- While currentLevel is not empty:
- Add all vertices in currentLevel to the result list.
- Create nextLevel = [].
- For each vertex u in currentLevel:
- For each neighbor v in adj[u]:
- If !visited[v]: mark visited[v] = true, append v to nextLevel.
- Set currentLevel = nextLevel.
- Return the result list.
#include <iostream>#include <vector> class Solution {public: std::vector<int> bfsOfGraph(int V, std::vector<std::vector<int>>& adj) { std::vector<bool> visited(V, false); std::vector<int> result; std::vector<int> currentLevel = {0}; visited[0] = true; while (!currentLevel.empty()) { std::vector<int> nextLevel; for (int u : currentLevel) { result.push_back(u); for (int v : adj[u]) { if (!visited[v]) { visited[v] = true; nextLevel.push_back(v); } } } currentLevel = std::move(nextLevel); } return result; }}; int main() { Solution sol; std::vector<std::vector<int>> adj = {{1, 2, 3}, {}, {4}, {}, {}}; std::vector<int> bfs = sol.bfsOfGraph(5, adj); std::cout << "BFS Traversal: "; for (int x : bfs) std::cout << x << " "; std::cout << "\nExpected: 0 1 2 3 4\n"; return 0;}Time & Space Complexity
- Time complexity:
O(V + E) - Space complexity:
O(V)