[Leetcode][第785题][JAVA][判断二分图][BFS][DFS]

【问题描述】[中等]

[Leetcode][第785题][JAVA][判断二分图][BFS][DFS]_第1张图片

【解答思路】

[Leetcode][第785题][JAVA][判断二分图][BFS][DFS]_第2张图片

1. DFS 深度优先遍历

时间复杂度:O(N+M) 空间复杂度:O(N)
[Leetcode][第785题][JAVA][判断二分图][BFS][DFS]_第3张图片

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 valid;

    public boolean isBipartite(int[][] graph) {
        int n = graph.length;
        valid = true;
        color = new int[n];
        Arrays.fill(color, UNCOLORED);
        for (int i = 0; i < n && valid; ++i) {
            if (color[i] == UNCOLORED) {
                dfs(i, RED, graph);
            }
        }
        return valid;
    }

    public void dfs(int node, int c, int[][] graph) {
        color[node] = c;
        int cNei = c == RED ? GREEN : RED;
        for (int neighbor : graph[node]) {
            if (color[neighbor] == UNCOLORED) {
                dfs(neighbor, cNei, graph);
                if (!valid) {
                    return;
                }
            } else if (color[neighbor] != cNei) {
                valid = false;
                return;
            }
        }
    }
}



2. 广度优先遍历 BFS

时间复杂度:O(N+M) 空间复杂度:O(N)
[Leetcode][第785题][JAVA][判断二分图][BFS][DFS]_第4张图片

class Solution {
    private static final int UNCOLORED = 0;
    private static final int RED = 1;
    private static final int GREEN = 2;
    private int[] color;

    public boolean isBipartite(int[][] graph) {
        int n = graph.length;
        color = new int[n];
        Arrays.fill(color, UNCOLORED);
        for (int i = 0; i < n; ++i) {
            if (color[i] == UNCOLORED) {
                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;
    }
}



【总结】

1. 深度优先遍历 栈/递归 广度优先遍历 队列
2有向图、无向图 、树 ----> BFS DFS思想

转载链接:https://leetcode-cn.com/problems/is-graph-bipartite/solution/pan-duan-er-fen-tu-by-leetcode-solution/

你可能感兴趣的:(刷题,java)