zoukankan      html  css  js  c++  java
  • 785. 判断二分图

    利用二分图没有奇环的性质
    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;
    	}
    };
    
  • 相关阅读:
    SQLyog连接MySQL8.0报2058错误的完美解决方法
    WPF之Binding深入探讨未参考
    C# SQLite 创建数据库的方法增删查改语法和命令
    winform实现INotifyPropertyChanged
    排序算法
    GitHub代码上传
    SQLyog
    Jenkins 部署 .NET MVC 项目
    Visual Studio 2019 代码规范
    C# SqlHelper类
  • 原文地址:https://www.cnblogs.com/Hunter01/p/13324467.html
Copyright © 2011-2022 走看看