Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 32 additions & 6 deletions problems/886.possible-bipartition.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,10 @@ dislikes[i][0] < dislikes[i][1]
我们用 1 表示互相不喜欢(dislike each other)。

```py
graph = [[0] * N for i in range(N)]
for a, b in dislikes:
graph[a - 1][b - 1] = 1
graph[b - 1][a - 1] = 1
graph = [[0] * N for i in range(N)]
for a, b in dislikes:
graph[a - 1][b - 1] = 1
graph[b - 1][a - 1] = 1
```

![image.png](https://tva1.sinaimg.cn/large/007S8ZIlly1ghlu5nd1cij30eo0d2tcg.jpg)
Expand Down Expand Up @@ -102,6 +102,28 @@ dislikes[i][0] < dislikes[i][1]
if colors[j] == 0 and not self.dfs(graph, colors, j, -1 * color, N)
```

最后有两个问题需要注意:

1. `if colors[i] == 0 and not self.dfs(graph, colors, i, 1, N)` 可以改为 `if colors[i] == 0 and not self.dfs(graph, colors, i, -1, N):` 么?

可以的。这不影响答案。假设改成 -1 后的染色分布情况已知,那么其染色分布情况等价于使用 1 的情况的反色(将颜色 1 替换为颜色-1,颜色-1 替换为颜色 1)而已。对是否可以二分图没有任何影响。

接上:那有没有可能使用颜色 1 推出矛盾,而使用颜色 -1 则推出成立呢?

没有可能。一次 dfs 处理的是一个子图。多次开启 dfs 不会相交,自然不存在这个问题。不信你可以将代码改成如下测试一下:

```py
for i in range(n):
if random.random() > 0.5:
if colors[i] == 0 and not dfs(i, -1): return False
else:
if colors[i] == 0 and not dfs(i, 1): return False
```

2. 为什么不需要 visited 数组来防止遍历过程中环的产生?

实际上,我们的 colors 数组就起到了 visited 的作用。如果 colors[i] == 0,因为着 visited[i] 为 False,否则为 True

## 关键点

- 二分图
Expand Down Expand Up @@ -139,8 +161,12 @@ class Solution:

**复杂度分析**

- 时间复杂度:$O(N^2)$
- 空间复杂度:$O(N)$
令 V 为点的个数。

最坏的情况下是稠密图,边的数量为点的数量的平方个。此时 graph 的空间为 $O(V^2)$, colors 空间为$O(V)$。由于需要遍历所有的点和边,因此时间复杂度为 $V+E$,由前面的分析最坏 E 是 $V^2$,因此空间复杂度为 $O(V^2)$

- 时间复杂度:$O(V^2)$
- 空间复杂度:$O(V^2)$

## 相关问题

Expand Down