码迷,mamicode.com
首页 > 其他好文 > 详细

785. 判断二分图

时间:2020-07-16 21:49:52      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:size   class   rap   turn   ++i   constexpr   ons   while   sign   

利用二分图没有奇环的性质
DFS:

class Solution {
private:
    static constexpr int UNCOLORED = 0;
    static constexpr int RED = 1;
    static constexpr int GREEN = 2;
    vector<int> color;
    bool valid;

public:
    void dfs(int node, int c, const vector<vector<int>>& graph) {
        color[node] = c;
        int cNei = 3-c;
        for (int neighbor: graph[node]) {
            if (color[neighbor] == UNCOLORED) {
                dfs(neighbor, cNei, graph);
                if (!valid) {
                    return;
                }
            }
            else if (color[neighbor] == c) {
                valid = false;
                return;
            }
        }
    }

    bool isBipartite(vector<vector<int>>& graph) {
        int n = graph.size();
        valid = true;
        color.assign(n, UNCOLORED);
        for (int i = 0; i < n && valid; ++i) {
            if (color[i] == UNCOLORED) {
                dfs(i, RED, graph);
            }
        }
        return valid;
    }
};


BFS:

class Solution {
public:
	bool isBipartite(vector<vector<int>>& graph) {
		int n = graph.size();
		vector<int> color(n, 0);
		for (int i = 0; i < n; ++i) {
			if (color[i] == 0) {
				queue<int> q;
				color[i] = 1;
				q.push(i);
				while (!q.empty())
				{
					int top = q.front(); q.pop();
					for (auto node : graph[top]) {
						if (color[node] == 0) {
							color[node] = 3-color[top];
							q.push(node);
						}
						else if (color[node] == color[top]) {
							return false;
						}
					}
				}
			}
		}
		return true;
	}
};

785. 判断二分图

标签:size   class   rap   turn   ++i   constexpr   ons   while   sign   

原文地址:https://www.cnblogs.com/Hunter01/p/13324467.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!