【Leetcode】785. Is Graph Bipartite?

35 篇文章 2 订阅
15 篇文章 0 订阅

Given an undirected graph, return true if and only if it is bipartite.

Recall that a graph is bipartite if we can split it's set of nodes into two independent subsets A and B such that every edge in the graph has one node in A and another node in B.

The graph is given in the following form: graph[i] is a list of indexes j for which the edge between nodes i and j exists.  Each node is an integer between 0 and graph.length - 1.  There are no self edges or parallel edges: graph[i] does not contain i, and it doesn't contain any element twice.

题意:判断是否是二分图,因为一条边两个点集合必定不同,也就是每个连通图中确定了一个点的集合后剩下的点集合必定是确定的,根据这一点用bfs和dfs即可,遇到集合不同时返回false最后返回true

dfs方法:

class Solution {
public:
    bool dfs(vector<vector<int>>& graph,vector<int>& color,int u,int co){
        if(color[u]!=0) return color[u]==co;
        color[u]=co;
        for(auto v:graph[u]){
            if(!dfs(graph,color,v,-co))return false;
        }
        return true;
    }
    bool isBipartite(vector<vector<int>>& graph) {
        vector<int> color(graph.size(),0);
        for(int i=0;i<graph.size();i++){
            if(color[i]==0&&!dfs(graph,color,i,1)) return false;
        }
        return true;
    }
};

bfs方法:

class Solution {
public:
    bool bfs(vector<vector<int>>& graph,vector<int>& color,int u,int co){
        if(color[u]!=0) return color[u]==co;
        queue<int> q;
        q.push(u);
        color[u]=co;
        while(!q.empty()){
            int v=q.front();
            q.pop();
            for(auto x:graph[v]){
                if(color[x]==color[v]) return false;
                if(color[x]!=0) continue;
                color[x]=-color[v];
                q.push(x);
            }
        }
        return true;
    }
    bool isBipartite(vector<vector<int>>& graph) {
        vector<int> color(graph.size(),0);
        for(int i=0;i<graph.size();i++){
            if(color[i]==0&&!bfs(graph,color,i,1)) return false;
        }
        return true;
    }
};

细节:dfs注意访问点时未访问的情况,bfs注意每个点取出来访问出度时遇到已经访问点的情况只要处理false的情况别忘了之后true的情况也要考虑否则下面对color的赋值会覆盖从而产生错误

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值