LeetCode785.判断二分图

在这里插入图片描述
思路:是标色题,二种颜色


class Solution {
    public boolean isBipartite(int[][] graph) {
        //标色题,DFS来标
        int[] color = new int[graph.length];
        for(int i = 0;i < graph.length;i++){
            //图需要遍历所有的节点来防止有孤立的点存在
            if(color[i] == 0){
                color[i] = -1;
                if(!dfs(i,graph,color)) return false;
            }
        }
        return true;
    }
    public boolean dfs(int k,int[][] graph,int[] color){
        int col = -color[k];
        for(int i = 0;i < graph[k].length;i++){
            if(color[graph[k][i]] == 0){
                color[graph[k][i]] = col;
                if(!dfs(graph[k][i],graph,color)) return false;
            }else if(color[graph[k][i]] != col){
                return false;
            }
        }
        return true;
    }
}
发布了169 篇原创文章 · 获赞 5 · 访问量 7674

猜你喜欢

转载自blog.csdn.net/fsdgfsf/article/details/104702496