File tree Expand file tree Collapse file tree 5 files changed +78
-0
lines changed
graphs/is-graph-bipartite Expand file tree Collapse file tree 5 files changed +78
-0
lines changed Original file line number Diff line number Diff line change 1+ from queue import Queue
2+
3+
4+ class Graph :
5+ def __init__ (self ):
6+ self ._vertices : list = []
7+ self ._colors : dict = {}
8+ self ._adjacency_matrix : dict = {}
9+
10+ def add_vertex (self , label : str ):
11+ self ._vertices .append (label )
12+ self ._colors [label ] = None
13+ self ._adjacency_matrix [label ]: list = []
14+
15+ def add_edge (self , label1 : str , label2 : str ):
16+ self ._adjacency_matrix [label1 ].append (label2 )
17+ self ._adjacency_matrix [label2 ].append (label1 )
18+
19+ def bipartite_check (self ) -> bool :
20+ for vertex in self ._vertices :
21+ if self ._colors [vertex ] is not None :
22+ continue
23+ self ._colors [vertex ] = "red"
24+ q : Queue = Queue ()
25+ q .enqueue (vertex )
26+ while not q .is_empty ():
27+ v = q .dequeue ()
28+ for neighbour in self ._adjacency_matrix [v ]:
29+ if self ._colors [neighbour ] == self ._colors [v ]:
30+ return False
31+ if self ._colors [neighbour ] is None :
32+ if self ._colors [v ] == "red" :
33+ self ._colors [neighbour ] = "blue"
34+ else :
35+ self ._colors [neighbour ] = "red"
36+ q .enqueue (neighbour )
37+ return True
38+
39+
40+
41+
42+
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 ())
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 )
You can’t perform that action at this time.
0 commit comments