Woodyiiiiiii / LeetCode

My private record of Leetcode solution

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Leetcode 785. Is Graph Bipartite?

Woodyiiiiiii opened this issue · comments

一、DFS解法
将相邻的节点染成相反的颜色,如果遍历时对应的颜色不是相反的,则说明不符合二分图Bipartite的定义:

// DFS
class Solution {

    private static final int UNCOLORED = 0;

    private static final int RED = 1;

    private static final int GREEN = 2;

    private int[] color;

    private boolean validate = true;

    public boolean isBipartite(int[][] graph) {

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

        for (int i = 0; i < n && validate; ++i) {

            if (color[i] != UNCOLORED) {
                continue;
            } 

            dfs(RED, i, graph);

        }

        return validate;

    }

    private void dfs(int c, int i, int[][] graph) {

        color[i] = c;
        int otherC = c == RED ? GREEN : RED;

        for (int a : graph[i]) {

            if (color[a] == UNCOLORED) {

                dfs(otherC, a, graph);

                if (!validate) {
                    return;
                }

            } else if (color[a] != otherC) {
                validate = false;
                return;
            }

        }
    }
}

二、BFS解法
宽度优先遍历,实际上我感觉跟DFS差不多的思路,不过访问顺序不同,维护一个队列来实现访问:

// BFS
class Solution {

    private static final int UNCOLORED = 0;

    private static final int RED = 1;

    private static final int GREEN = 2;

    private int[] color;

    private boolean validate = true;

    public boolean isBipartite(int[][] graph) {

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

        for (int i = 0; i < n && validate; ++i) {

            if (color[i] != UNCOLORED) {
                continue;
            } 

            Queue<Integer> queue = new LinkedList<Integer>();
            queue.offer(i);
            color[i] = RED;
            while (!queue.isEmpty()) {
                int node = queue.poll();
                int cNei = color[node] == RED ? GREEN : RED;
                for (int neighbor : graph[node]) {
                    if (color[neighbor] == UNCOLORED) {
                        queue.offer(neighbor);
                        color[neighbor] = cNei;
                    } else if (color[neighbor] != cNei) {
                        return false;
                    }
                }
            }

        }

        return true;

    }

}