LeetCode 785. 判断二分图

LeetCode 785. 判断二分图

思路

染色问题,很简单,dfs对附近的点走下一个颜色,如果下一个颜色冲突返回false,本个也就直接false。
问题一般出在只对一个点进行dfs,因为是无向环图,所以可能出现子图无法被第一个点访问到的问题,所以要对
所有点进行dfs染色。

代码

class Solution {
    public int [] color;
    public int [][] graph;
    public boolean isBipartite(int[][] graph) {
        if(graph.length==0)return false;this.graph=graph;
        color=new int[graph.length];
        //初始化,-1代表本地方未染色
        for(int i =0;i<color.length;i++){
            color[i]=-1;
        }
        //这里代码报错,因为可能会有区间的错误,空的点也是需要染色的
        for(int i =0;i<graph.length;i++){
            if(graph[i].length!=0&&color[i]==-1){
                for(int k =0;k<graph[i].length;k++){
                    if(!isOkay(-1,graph[i][k],0))return false;
                }
            }
        }
        return true;
    }
    public boolean isOkay(int from,int to,int nextcolor){
        // System.out.println(to);
        //已染色,但是冲突
        if(color[to]!=nextcolor&&color[to]!=-1){return false;}
        //已染色,未冲突
        if(color[to]!=-1)return true;
        //未染色,对区域进行染色
            color[to]=nextcolor;
            //切换为下一个颜色,0,1 取模改变颜色
            nextcolor=(nextcolor+1)%2;
            for(int i=0;i<this.graph[to].length;i++){
                if(!isOkay(to,graph[to][i],nextcolor)){
                    return false;
                }
            }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42499133/article/details/107374339