Graph Bipartite

leetcode785 判断graph是否Bipartite
题目链接:https://leetcode.com/problems/is-graph-bipartite/description/

一个图为Bipartite当且仅当图的节点能分出两个不相交的顶点集合A和B,图中的任意一条边的两个端点不能在同一个集合中。
需要注意的地方:
1.如果一个顶点没有边也是可以的。
2.图可以分离为多个Bipartite图,即是多个满足Bipartite的连通图

解决方法:
BFS:

class Solution {
    public boolean isBipartite(int[][] graph) {
        if(graph == null || graph.length == 0)  return true;

        int nodeCount = graph.length;
        int[] color = new int[nodeCount];

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

        return true;
    }
    public boolean isBipartiteFunc(int[][] graph, int[] color, int src){
        Queue<Integer> queue = new LinkedList<>();
        color[src] = 0;
        queue.add(src);
        while(!queue.isEmpty()){
            int node = queue.poll();
            for(int v : graph[node]){
                if(color[v] == -1){
                    color[v] = 1 - color[node];
                    queue.offer(v);
                }else if(color[v] == color[node]){
                    return false;
                }
            }
        }

        return true;
    }    
}

DFS:

class Solution {
    public boolean isBipartite(int[][] graph) {
        int V = graph.length;
        if (V <= 1) return true;

        Boolean[] colors = new Boolean[V];
        for (int i = 0; i < V; i++) if (colors[i] == null && !color (graph, colors, true, i))
            return false;

        return true;
    }

    boolean color (int[][] graph, Boolean[] colors, Boolean color, int node) {
        if (colors[node] != null)   return colors[node] == color;

        colors[node] = color;
        color = !color;
        for (int neighbor : graph[node]) {
            if (!color (graph, colors, color, neighbor))
                return false;
        }

        return true;
    }
}

如果你对这个算法感兴趣,那么以下链接会有帮助:
geekforgeek的bipartite graph
https://www.geeksforgeeks.org/bipartite-graph/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值