785. 判断二分图

  判断二分图,使用染色法

 方法一:BFS

public boolean isBipartite(int[][] graph) {
        int n = graph.length;
        int[] color = new int[n];  // 染色数组 0表示为染色, 1 -1为不同色
        for(int i = 0; i < n; i++) { // 每个位置开始,进行BFS染色
            if(color[i] != 0) continue;
            color[i] = 1;
            Deque<Integer> queue = new LinkedList<>();
            queue.add(i);
            while(!queue.isEmpty()) {
                int num = queue.poll();
                for(int j = 0; j < graph[num].length; j++) {
                    if(color[graph[num][j]] == color[num]) return false;
                    else if (color[graph[num][j]] == 0) {
                        color[graph[num][j]] = -color[num];
                        queue.add(graph[num][j]);
                    }
                }
            }
        }
        return true;
    }

方法二:DFS

    public boolean isBipartite(int[][] graph) {
        int n = graph.length;
        int[] color = new int[n];
        for(int i = 0; i < n; i++) {   // 每个位置进行DFS染色
            if(color[i] != 0) continue;
            if(!dfs(graph,i,color,1)) return false;
        }
        return true;
    }                                 // num为当前点 color为染色数组 pre为上一个颜色
    public boolean dfs(int[][] graph, int num, int[] color, int pre) {
        if(color[num] == pre) return false;
        if(color[num] == -pre) return true;
        color[num] = -pre;
        for(int i = 0; i < graph[num].length; i++) {
            if(!dfs(graph,graph[num][i],color,-pre)) return false;
        }
        return true;
    }
原文地址:https://www.cnblogs.com/yonezu/p/13322727.html