File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change
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
+ """
You can’t perform that action at this time.
0 commit comments