File tree Expand file tree Collapse file tree 3 files changed +85
-0
lines changed
Ch07. Graphs and Graph Algorithms/is-graph-bipartite Expand file tree Collapse file tree 3 files changed +85
-0
lines changed Original file line number Diff line number Diff line change 1+ from queue import Queue
2+
3+ class Graph :
4+ def __init__ (self ):
5+ self .__vertices__ :dict = {}
6+ self .__adjacency_map__ : dict = {}
7+ self .__colors__ : dict = {}
8+ self .__colors__ ["red" ]: list = []
9+ self .__colors__ ["blue" ]: list = []
10+
11+
12+ def add_vertex (self , vertex : str ):
13+ self .__vertices__ [vertex ] = vertex
14+ self .__adjacency_map__ [vertex ]:list = []
15+
16+ def add_edge (self , vertex1 : str , vertex2 : str ):
17+ self .__adjacency_map__ [vertex1 ].append (vertex2 )
18+ self .__adjacency_map__ [vertex2 ].append (vertex1 )
19+
20+ def bipartite_check (self , vertex ) -> bool :
21+ q : Queue = Queue ()
22+ for vertex in self .__vertices__ :
23+ if vertex in self .__colors__ ["red" ] or vertex in self .__colors__ ["blue" ]:
24+ continue
25+ self .__colors__ ["red" ].append (vertex )
26+ q .enqueue (vertex )
27+
28+ while not q .is_empty ():
29+ tmp : str = q .dequeue ()
30+ if tmp in self .__colors__ ["red" ]:
31+ current_color = "red"
32+ opposite_color = "blue"
33+ else :
34+ current_color = "blue"
35+ opposite_color = "red"
36+ for neighbour in self .__adjacency_map__ [tmp ]:
37+ if neighbour in self .__colors__ [current_color ]:
38+ return False
39+ if neighbour not in self .__colors__ [opposite_color ]:
40+ self .__colors__ [opposite_color ].append (neighbour )
41+ q .enqueue (neighbour )
42+ return True
43+
44+
45+
Original file line number Diff line number Diff line change 1+ from graph import Graph
2+
3+
4+ g : Graph = Graph ()
5+ g .add_vertex ("a" )
6+ g .add_vertex ("b" )
7+ g .add_vertex ("c" )
8+ g .add_vertex ("d" )
9+
10+ # a, b ||---|| c, d
11+
12+
13+ g .add_edge ("a" , "c" )
14+ g .add_edge ("a" , "d" )
15+
16+ g .add_edge ("b" , "c" )
17+ g .add_edge ("b" , "d" )
18+
19+
20+ # g.add_edge("a", "b")
21+
22+ print (g .bipartite_check ("a" ))
23+
24+
Original file line number Diff line number Diff line change 1+ class Queue :
2+ def __init__ (self ):
3+ self .__queue__ : list = []
4+
5+ def is_empty (self ) -> bool :
6+ return len (self .__queue__ ) == 0
7+
8+ def enqueue (self , vertex : str ):
9+ self .__queue__ .append (vertex )
10+
11+ def dequeue (self ):
12+ if self .is_empty ():
13+ raise Exception ("Queue is empty" )
14+ return self .__queue__ .pop (0 )
15+
16+
You can’t perform that action at this time.
0 commit comments