Skip to content

Commit 69470c8

Browse files
committed
[Add] Leetcode > 785. Is Graph Bipartite?
1 parent 0d22f4b commit 69470c8

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

Leetcode/is_graph_bipartite.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
# 785. Is Graph Bipartite?
2+
3+
from collections import deque
4+
class Solution:
5+
def isBipartite(self, graph: List[List[int]]) -> bool:
6+
n = len(graph)
7+
self.nodes = [-1]*n
8+
def bfs(s):
9+
self.nodes[s] = 0
10+
q = deque([s])
11+
while q:
12+
cur = q.popleft()
13+
for t in graph[cur]:
14+
if self.nodes[t] == -1:
15+
self.nodes[t] = self.nodes[cur] + 1
16+
q.append(t)
17+
elif self.nodes[t] == self.nodes[cur]:
18+
return False
19+
return True
20+
return all(bfs(v) for v in range(n) if self.nodes[v] == -1)

0 commit comments

Comments
 (0)