1. Iterative BFS with (Node, Parent) Queue
Intuition
Push (startNode, -1) into the queue and mark it visited. For every dequeued (u, parent), check its neighbors. If neighbor is unvisited, mark it visited and push (neighbor, u). If neighbor is already visited and neighbor != parent, a cycle is detected.
Algorithm
- Initialize visited array of size V to false.
- Loop i from 0 to V - 1:
- If !visited[i]:
- visited[i] = true.
- Queue q pushes (i, -1).
- While queue is not empty:
- Pop (u, parent) from q.
- For each neighbor v in adj[u]:
- If !visited[v]:
- visited[v] = true.
- q.push((v, u)).
- Else if v != parent:
- Return true (cycle found).
- Return false.
#include <iostream>#include <vector>#include <queue> class Solution {public: bool isCycle(int V, std::vector<std::vector<int>>& adj) { std::vector<bool> visited(V, false); for (int i = 0; i < V; ++i) { if (!visited[i]) { std::queue<std::pair<int, int>> q; visited[i] = true; q.push({i, -1}); while (!q.empty()) { auto [u, parent] = q.front(); q.pop(); for (int v : adj[u]) { if (!visited[v]) { visited[v] = true; q.push({v, u}); } else if (v != parent) { return true; // Cycle detected } } } } } return false; }}; int main() { Solution sol; std::vector<std::vector<int>> adj = {{1}, {0, 2, 4}, {1, 3}, {2, 4}, {1, 3}}; std::cout << "BFS Cycle: " << (sol.isCycle(5, adj) ? "true" : "false") << " (Expected: true)\n"; return 0;}Time & Space Complexity
- Time complexity:
O(V + E) - Space complexity:
O(V)