886. 可能的二分法(二分图染色)

class Solution {
    int[] color;
    Map<Integer,List<Integer>> map;
    public boolean possibleBipartition(int N, int[][] dislikes) {
        map = new HashMap<>();
        color = new int[N+1];
        for(int[] d : dislikes) {
            map.computeIfAbsent(d[0],k->new ArrayList<>()).add(d[1]);
            map.computeIfAbsent(d[1],k->new ArrayList<>()).add(d[0]);
        }
        for(int i = 1; i <= N; i++) {  // 每个点都要出发进行dfs染色
            if(color[i] != 0) continue;
            if(!dfs(i,1)) return false; // 染成1 2两种颜色
        }
        return true;

    }
    public boolean dfs(int u, int c) {
        color[u] = c;
        if(!map.containsKey(u)) return true;
        for(int k : map.get(u)) {
            if(color[k] != 0) {
                if(color[k] == c) {
                    return false;
                }
            } else {
                if(!dfs(k,3-c)) return false;
            }
        }
        return true;
    }
}

 

posted @ 2020-08-18 16:22  Sexyomaru  阅读(175)  评论(0)    收藏  举报