@@ -61,10 +61,10 @@ dislikes[i][0] < dislikes[i][1]
61
61
我们用 1 表示互相不喜欢(dislike each other)。
62
62
63
63
``` py
64
- graph = [[0 ] * N for i in range (N)]
65
- for a, b in dislikes:
66
- graph[a - 1 ][b - 1 ] = 1
67
- graph[b - 1 ][a - 1 ] = 1
64
+ graph = [[0 ] * N for i in range (N)]
65
+ for a, b in dislikes:
66
+ graph[a - 1 ][b - 1 ] = 1
67
+ graph[b - 1 ][a - 1 ] = 1
68
68
```
69
69
70
70
![ image.png] ( https://tva1.sinaimg.cn/large/007S8ZIlly1ghlu5nd1cij30eo0d2tcg.jpg )
@@ -102,6 +102,28 @@ dislikes[i][0] < dislikes[i][1]
102
102
if colors[j] == 0 and not self .dfs(graph, colors, j, - 1 * color, N)
103
103
```
104
104
105
+ 最后有两个问题需要注意:
106
+
107
+ 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): ` 么?
108
+
109
+ 可以的。这不影响答案。假设改成 -1 后的染色分布情况已知,那么其染色分布情况等价于使用 1 的情况的反色(将颜色 1 替换为颜色-1,颜色-1 替换为颜色 1)而已。对是否可以二分图没有任何影响。
110
+
111
+ 接上:那有没有可能使用颜色 1 推出矛盾,而使用颜色 -1 则推出成立呢?
112
+
113
+ 没有可能。一次 dfs 处理的是一个子图。多次开启 dfs 不会相交,自然不存在这个问题。不信你可以将代码改成如下测试一下:
114
+
115
+ ``` py
116
+ for i in range (n):
117
+ if random.random() > 0.5 :
118
+ if colors[i] == 0 and not dfs(i, - 1 ): return False
119
+ else :
120
+ if colors[i] == 0 and not dfs(i, 1 ): return False
121
+ ```
122
+
123
+ 2 . 为什么不需要 visited 数组来防止遍历过程中环的产生?
124
+
125
+ 实际上,我们的 colors 数组就起到了 visited 的作用。如果 colors[ i] == 0,因为着 visited[ i] 为 False,否则为 True
126
+
105
127
## 关键点
106
128
107
129
- 二分图
@@ -139,8 +161,12 @@ class Solution:
139
161
140
162
** 复杂度分析**
141
163
142
- - 时间复杂度:$O(N^2)$
143
- - 空间复杂度:$O(N)$
164
+ 令 V 为点的个数。
165
+
166
+ 最坏的情况下是稠密图,边的数量为点的数量的平方个。此时 graph 的空间为 $O(V^2)$, colors 空间为$O(V)$。由于需要遍历所有的点和边,因此时间复杂度为 $V+E$,由前面的分析最坏 E 是 $V^2$,因此空间复杂度为 $O(V^2)$
167
+
168
+ - 时间复杂度:$O(V^2)$
169
+ - 空间复杂度:$O(V^2)$
144
170
145
171
## 相关问题
146
172
0 commit comments