Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 785. Is Graph Bipartite? #105

Open
Woodyiiiiiii opened this issue Apr 29, 2022 · 0 comments
Open

Leetcode 785. Is Graph Bipartite? #105

Woodyiiiiiii opened this issue Apr 29, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

一、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;

    }

}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant