# \[785]\[中等]\[BFS]\[DFS]\[并查集] 判断二分图

## 题目描述

[785. 判断二分图](https://leetcode-cn.com/problems/is-graph-bipartite/)

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

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

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

示例 1:

```
输入: [[1,3], [0,2], [1,3], [0,2]]
输出: true
解释:
无向图如下:
0----1
|    |
|    |
3----2
我们可以将节点分成两组: {0, 2} 和 {1, 3}。
```

示例 2:

```
输入: [[1,2,3], [0,2], [0,1,3], [0,2]]
输出: false
解释:
无向图如下:
0----1
| \  |
|  \ |
3----2
我们不能将节点分割成两个独立的子集。
```

注意:

* graph 的长度范围为 \[1, 100]。
* graph\[i] 中的元素的范围为 \[0, graph.length - 1]。
* graph\[i] 不会包含 i 或者有重复的值。
* 图是无向的: 如果j 在 graph\[i]里边, 那么 i 也会在 graph\[j]里边。

## 解题思路

* [判断二分图](https://leetcode-cn.com/problems/is-graph-bipartite/solution/pan-duan-er-fen-tu-by-leetcode-solution/)
* [BFS + DFS + 并查集，三种方法判断二分图](https://leetcode-cn.com/problems/is-graph-bipartite/solution/bfs-dfs-bing-cha-ji-san-chong-fang-fa-pan-duan-er-/)

### DFS

如果给定的无向图连通，那么我们就可以任选一个节点开始，给它染成红色。随后我们对整个图进行遍历，将该节点直接相连的所有节点染成绿色，表示这些节点不能与起始节点属于同一个集合。我们再将这些绿色节点直接相连的所有节点染成红色，以此类推，直到无向图中的每个节点均被染色。

如果我们能够成功染色，那么红色和绿色的节点各属于一个集合，这个无向图就是一个二分图；如果我们未能成功染色，即在染色的过程中，某一时刻访问到了一个已经染色的节点，并且它的颜色与我们将要给它染上的颜色不相同，也就说明这个无向图不是一个二分图。

算法的流程如下：

* 我们任选一个节点开始，将其染成红色，并从该节点开始对整个无向图进行遍历；
* 在遍历的过程中，如果我们通过节点`u`遍历到了节点`v`（即`u`和`v`在图中有一条边直接相连），那么会有两种情况：
  * 如果 `v` 未被染色，那么我们将其染成与 `u` 不同的颜色，并对 `v` 直接相连的节点进行遍历；
    * 如果 `v` 被染色，并且颜色与 `u` 相同，那么说明给定的无向图不是二分图。我们可以直接退出遍历并返回 `False` 作为答案。
* 当遍历结束时，说明给定的无向图是二分图，返回 `True` 作为答案。

深度优先搜索或广度优先搜索对, 都是使用这个思路.

DFS的代码:

```python
class Solution:
    def isBipartite(self, graph: List[List[int]]) -> bool:
        n = len(graph)
        UNCOLORED, RED, GREEN = 0, 1, 2
        colors = [UNCOLORED] * n

        def dfs(node, color):
            """
            code: 当前结点
            color: 当前结点应染颜色
            """
            colors[node] = color
            color_next = GREEN if color == RED else RED
            for neighbor in graph[node]:
                if colors[neighbor] == UNCOLORED:
                    if not dfs(neighbor, color_next):
                        return False
                elif colors[neighbor] != color_next:
                    return False
            return True

        for i in range(n):
            if colors[i] == UNCOLORED:
                if not dfs(i, RED):
                    return False
        return True
```

### BFS

借助队列实现.

```python
class Solution:
    def isBipartite(self, graph: List[List[int]]) -> bool:
        n = len(graph)
        UNCOLORED, RED, GREEN = 0, 1, 2
        colors = [UNCOLORED] * n

        q = collections.deque()

        for i in range(n):
            if colors[i] == UNCOLORED:
                q.append(i)
                colors[i] = RED
                while q:
                    node = q.popleft()
                    color_neighbor = GREEN if colors[node] == RED else RED
                    for neighbor in graph[node]:
                        if colors[neighbor] == UNCOLORED:
                            colors[neighbor] = color_neighbor
                            q.append(neighbor)
                        elif colors[neighbor] != color_neighbor:
                            return False
        return True
```

### 并查集

我们知道如果是二分图的话，那么图中每个顶点的所有邻接点都应该属于同一集合，且不与顶点处于同一集合。因此我们可以使用并查集来解决这个问题，我们遍历图中每个顶点，将当前顶点的所有邻接点进行合并，并判断这些邻接点中是否存在某一邻接点已经和当前顶点处于同一个集合中了，若是，则说明不是二分图。

```python
class UnionFind:
    def __init__(self, n):
        self.root = list(range(n))

    def find(self, i):
        if self.root[i] == i:
            return i
        self.root[i] = self.find(self.root[i])
        return self.root[i]

    def union(self, i, j):
        self.root[self.find(i)] = self.find(j)

    def is_connected(self, i, j):
        return self.find(i) == self.find(j)


class Solution:
    def isBipartite(self, graph: List[List[int]]) -> bool:
        n = len(graph)
        uf = UnionFind(n)

        for i in range(n):
            nodes = graph[i]
            for neighbor in nodes:
                if uf.is_connected(i, neighbor):
                    return False
                uf.union(nodes[0], neighbor)
        return True
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kerasnoone.gitbook.io/garnet/suan-fa/tu/785-pan-duan-er-fen-tu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
