1. Iterative BFS 2-Coloring
Intuition
Initialize all node colors to -1. For each uncolored node i, color it 0, push to queue, and expand. If an uncolored neighbor is found, assign color 1 - currColor and enqueue. If an already-colored neighbor has the same color, return false.
Algorithm
- Initialize color array of size n to -1.
- Loop i from 0 to n - 1:
- If color[i] == -1:
- color[i] = 0.
- Initialize queue q and push i.
- While queue is not empty:
- Pop u from q.
- For each neighbor v in graph[u]:
- If color[v] == -1:
- color[v] = 1 - color[u].
- Push v into q.
- Else if color[v] == color[u]:
- Return false (odd cycle detected).
- Return true.
#include <iostream>#include <vector>#include <queue> class Solution {public: bool isBipartite(std::vector<std::vector<int>>& graph) { int n = graph.size(); std::vector<int> color(n, -1); for (int i = 0; i < n; ++i) { if (color[i] == -1) { color[i] = 0; std::queue<int> q; q.push(i); while (!q.empty()) { int u = q.front(); q.pop(); for (int v : graph[u]) { if (color[v] == -1) { color[v] = 1 - color[u]; q.push(v); } else if (color[v] == color[u]) { return false; // Odd cycle detected } } } } } return true; }}; int main() { Solution sol; std::vector<std::vector<int>> g1 = {{1, 3}, {0, 2}, {1, 3}, {0, 2}}; std::vector<std::vector<int>> g2 = {{1, 2, 3}, {0, 2}, {0, 1, 3}, {0, 2}}; std::cout << "Graph 1 Bipartite: " << (sol.isBipartite(g1) ? "true" : "false") << " (Expected: true)\n"; std::cout << "Graph 2 Bipartite: " << (sol.isBipartite(g2) ? "true" : "false") << " (Expected: false)\n"; return 0;}Time & Space Complexity
- Time complexity:
O(V + E) - Space complexity:
O(V)