Skip to content

Commit eefcf52

Browse files
authored
Update 785.is-graph-bipartite.md
1 parent bee58af commit eefcf52

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

problems/785.is-graph-bipartite.md

+19
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,25 @@ class Solution:
105105
- 时间复杂度:$O(N^2)$
106106
- 空间复杂度:$O(N)$
107107

108+
109+
如上代码并不优雅,之所以这么写只是为了体现和 886 题一致性。一个更加优雅的方式是不建立 grid,而是利用题目给的 graph(邻接矩阵)。
110+
111+
```py
112+
class Solution:
113+
def isBipartite(self, graph: List[List[int]]) -> bool:
114+
n = len(graph)
115+
colors = [0] * n
116+
def dfs(i, color):
117+
colors[i] = color
118+
for neibor in graph[i]:
119+
if colors[neibor] == color: return False
120+
if colors[neibor] == 0 and not dfs(neibor,-1*color): return False
121+
return True
122+
for i in range(n):
123+
if colors[i] == 0 and not dfs(i,1): return False
124+
return True
125+
```
126+
108127
## 相关问题
109128

110129
- [886. 可能的二分法](./886.possible-bipartition.md)

0 commit comments

Comments
 (0)