leetcode785+二部图染色问题,BFS

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013554860/article/details/87562087

https://leetcode.com/problems/is-graph-bipartite/

class Solution {
public:
    bool isBipartite(vector<vector<int>>& graph) {
        vector<int> colors(graph.size());
        for(int i=0; i<graph.size(); i++){
            if(colors[i]!=0) continue;
            colors[i] = 1;
            queue<int> Q;
            Q.push(i);
            while (!Q.empty()) {
                int t = Q.front(); Q.pop();
                for(auto a: graph[t]){
                    if(colors[a]==colors[t]) return false;  //相同颜色
                    if(colors[a]==0){
                        colors[a] = -1*colors[t]; //换成不同颜色
                        Q.push(a);
                    }
                }
            }
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/u013554860/article/details/87562087