首页 > 技术文章 > May LeetCoding Challenge27 之 二分图

yawenw 2020-06-01 19:02 原文

二分图问题:首先要用HashMap构造图结构。然后用colors数组表示结染色情况。

遍历N个结点,从N个结点分别出发进行染色尝试,进行递归。

如果结点没有被染色并且不能被染成指定的颜色,返回失败。

对结点的dislike邻居结点进行递归,递归过程中,如果该结点已经被染色,返回是否和想要染的颜色相等。如果没被染色,将结点染上色。如果当前结点没有dislike,直接返回true。

class Solution {
    Map<Integer, Set<Integer>> graph = new HashMap<>();
    int[] colors;
    public boolean possibleBipartition(int N, int[][] dislikes) {
        colors = new int[N+1];//每个结点的颜色,初始化为'0'色
        for(int[] nums: dislikes){//构造图关系
            int a = nums[0];
            int b = nums[1];
            graph.putIfAbsent(a, new HashSet<Integer>());
            graph.putIfAbsent(b, new HashSet<Integer>());
            graph.get(a).add(b);
            graph.get(b).add(a);
        }
        for(int i = 1; i <= N; i++){//从1开始对N个结点染色
            if(colors[i] == 0 && !paintcolor(i, 1))
                return false;
        }
        return true;
    }
    public boolean paintcolor(int node, int color){
        if(colors[node] != 0) return colors[node] == color;//如果不是初始化'0'颜色,判断当前是否和要染的色一样
        colors[node] = color; //如果是初始化'0'颜色,对当前结点染色
        if(graph.get(node) == null) return true;//如果当前结点没有dislikes结点,返回true
        for(int next: graph.get(node)){
            if(!paintcolor(next, -color)) return false;
        }
        return true;
    }
}

 

推荐阅读