判断二分图

题目:判断二分图

问题描述:

给定一个无向图graph,当这个图为二分图时返回true。

如果我们能将一个图的节点集合分割成两个独立的子集A和B,并使图中的每一条边的两个节点一个来自A集合,一个来自B集合,我们就将这个图称为二分图。

graph将会以邻接表方式给出,graph[i]表示图中与节点i相连的所有节点。每个节点都是一个在0到graph.length-1之间的整数。这图中没有自环和平行边: graph[i] 中不存在i,并且graph[i]中没有重复的值。

示例:

见LeetCode判断二分图

解决代码:


public class isBipartiteTest {

    public boolean isBipartite(int[][] graph) {
        // 无向图节点数量
        int nodeNum = graph.length;
        // 无向图中节点以及邻节点的着色情况
        int[] color = new int[nodeNum];
        // 此处只要初始化为除 0 或 1 之外的数即可
        Arrays.fill(color, -1);

        for(int i = 0; i < nodeNum; i++) {
            // 若当前节点还未着色
            if(color[i] == -1) {
                Stack<Integer> stack = new Stack<>();
                // 将当前节点入栈
                stack.push(i);
                // 为当前节点着色为 1
                color[i] = 0;

                // 直到当前节点以及其所有邻节点均已着色完毕后退出循环
                while(!stack.isEmpty()) {
                    int node = stack.pop();
                    // 遍历当前节点的所有邻节点的着色情况
                    for(int nei : graph[node]) {
                        // 若当前邻节点还未着色
                        if(color[nei] == -1) {
                            // 将当前邻节点入栈
                            stack.push(nei);
                            // 可保证当前邻节点与当前节点的着色情况不同
                            color[nei] = color[node] ^ 1;
                        } else if(color[nei] == color[node]) {  // 当前节点与邻节点着色相同,不是二分图,直接返回结果
                            return false;
                        }
                    }

                }
            }
        }

        return true;
    }
}

posted @ 2020-09-08 13:22  samsaraaa  阅读(111)  评论(0编辑  收藏  举报