@@ -61,10 +61,10 @@ dislikes[i][0] < dislikes[i][1]
6161我们用 1 表示互相不喜欢(dislike each other)。
6262
6363``` 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
6868```
6969
7070![ image.png] ( https://tva1.sinaimg.cn/large/007S8ZIlly1ghlu5nd1cij30eo0d2tcg.jpg )
@@ -102,6 +102,28 @@ dislikes[i][0] < dislikes[i][1]
102102if colors[j] == 0 and not self .dfs(graph, colors, j, - 1 * color, N)
103103```
104104
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+
105127## 关键点
106128
107129- 二分图
@@ -139,8 +161,12 @@ class Solution:
139161
140162** 复杂度分析**
141163
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)$
144170
145171## 相关问题
146172
0 commit comments