Skip to content

Commit 8fe6976

Browse files
author
Chris Wu
committed
no message
1 parent f05cd51 commit 8fe6976

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

problems/is-graph-bipartite.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
from collections import defaultdict
2+
3+
class Solution(object):
4+
def isBipartite(self, graph):
5+
if not graph: return True
6+
7+
A, B = set(), set()
8+
stack = []
9+
10+
for node in xrange(len(graph)): #[1]
11+
#check if visited, if not start DFS by putting it to stack
12+
if node not in A and node not in B:
13+
stack.append(node)
14+
A.add(node)
15+
16+
while stack: #[0]
17+
n = stack.pop()
18+
if n in A:
19+
for nei in graph[n]:
20+
if nei in A: return False
21+
if nei not in B:
22+
stack.append(nei)
23+
B.add(nei)
24+
elif n in B:
25+
for nei in graph[n]:
26+
if nei in B: return False
27+
if nei not in A:
28+
stack.append(nei)
29+
A.add(nei)
30+
return True
31+
"""
32+
Use DFS to travserse each node [0]
33+
If the node is in A, all its children should be in B.
34+
If the node is in B, all its children should be in A.
35+
36+
Not necessary all the nodes in graph are connected. [1]
37+
So we still need to loop the node to check if it is visited.
38+
"""

0 commit comments

Comments
 (0)