Is Graph Bipartite?

 avatar
unknown
c_cpp
2 years ago
793 B
3
Indexable
class Solution {
public:
    bool isBipartite(vector<vector<int>>& graph) {
        vector<int> color(graph.size(), 0);
        vector<bool> vis(graph.size(), false);
        stack<int> q;
        for(int i = 0; i < graph.size(); i++) {
            if(vis[i]) continue;
            color[i] = 1;
            vis[i] = true;
            q.push(i);
            while(!q.empty()) {
                int curr = q.top();
                q.pop();
                for(auto x : graph[curr]) {
                    if(color[x] == color[curr]) return false;
                    if(vis[x]) continue;
                    color[x] = -color[curr];
                    vis[x] = true;
                    q.push(x);
                }
            }
        }
        return true;
    }
};