剑指offer 专项突破版 106、二分图

题目链接

思路
  • 这个题仍然是注意思路,把二分图转化为给顶点涂色
  • 如果每一条边所依附的两个顶点都是不同的颜色 那么他就是一个二分图
  • 所以我们的搜索模板 最外层是遍历所有的顶点 如果该顶点尚未上色 就调用辅助函数
  • 对于辅助函数 我们先给该顶点上色 然后依次处理和该顶点相邻的所有顶点
    • 如果相邻的顶点涂色了 判断是否和当前顶点颜色相反
    • 如果没有涂色 那就对该顶点递归调用辅助函数

递归

class Solution {
    public boolean isBipartite(int[][] graph) {
		
        int[] color = new int[graph.length];
		Arrays.fill(color,-1);

        for(int i = 0 ; i < graph.length ; i++){
            if(-1 == color[i]){
                if(!dfs(graph,color,i,0))
                	return false;
            }
        }

        return true;
    }

	private boolean dfs(int[][] graph , int[] colors , int i , int color){

        if(colors[i] >= 0){
            return colors[i] == color;
        }
        
        colors[i] = color;

		for(int index : graph[i]){
            if(!dfs(graph,colors,index,1-color)){
                return false;
            }
        }

        return true;
    }
}

迭代~

class Solution {
    public boolean isBipartite(int[][] graph) {
		
        int[] color = new int[graph.length];
		Arrays.fill(color,-1);

        for(int i = 0 ; i < graph.length ; i++){
            if(-1 == color[i]){
                if(!dfs(graph,color,i,0))
                	return false;
            }
        }

        return true;
    }

	private boolean dfs(int[][] graph , int[] colors , int i , int color){

        Queue<Integer> queue = new LinkedList();
		queue.offer(i);
		colors[i] = color;

        while(!queue.isEmpty()){
			int index = queue.poll();
            color = 1 - colors[index];

            for(int j : graph[index]){
				if(-1 == colors[j]){
                    colors[j] = color;
                    queue.offer(j);
                }else if (color != colors[j])
                	return false;
            }
        }

        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值