22
33class Graph :
44 def __init__ (self ):
5- self .__vertices__ :dict = {}
6- self .__adjacency_map__ : dict = {}
5+ self .__vertices__ : list = []
6+ self .__adjacency_list__ : dict = {}
77 self .__colors__ : dict = {}
8- self .__colors__ ["red" ]: list = []
9- self .__colors__ ["blue" ]: list = []
108
9+ def add_vertex (self , label : str ):
10+ self .__vertices__ .append (label )
11+ self .__adjacency_list__ [label ]: list = []
1112
12- def add_vertex (self , vertex : str ):
13- self .__vertices__ [ vertex ] = vertex
14- self .__adjacency_map__ [ vertex ]: list = []
13+ def add_edge (self , label1 : str , label2 : str ):
14+ self .__adjacency_list__ [ label1 ]. append ( label2 )
15+ self .__adjacency_list__ [ label2 ]. append ( label1 )
1516
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 ()
17+ def is_bipartite (self ) -> bool :
2218 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 )
19+ if vertex not in self .__colors__ :
20+ self .__colors__ [vertex ] = "red"
21+ q : Queue = Queue ()
22+ q .enqueue (vertex )
23+
24+ current : str = None
25+ while not q .is_empty ():
26+ current = q .dequeue ()
27+ for neighbour in self .__adjacency_list__ [current ]:
28+ if neighbour not in self .__colors__ :
29+ if self .__colors__ [current ] == "red" :
30+ self .__colors__ [neighbour ] = "blue"
31+ else :
32+ self .__colors__ [neighbour ] = "red"
33+ q .enqueue (neighbour )
34+ else :
35+ if self .__colors__ [neighbour ] == self .__colors__ [current ]:
36+ return False
4237 return True
43-
44-
45-
38+
0 commit comments