|
3 | 3 |
|
4 | 4 | class Graph: |
5 | 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: |
| 6 | + self.vertices: list = [] |
| 7 | + self.adjacency_list: dict = {} |
| 8 | + self.color: dict = {} |
| 9 | + |
| 10 | + def add_vertex(self, label: str = None): |
| 11 | + self.vertices.append(label) |
| 12 | + self.adjacency_list[label]: list = [] |
| 13 | + self.color[label] = None |
| 14 | + |
| 15 | + def add_edge(self, label1: str = None, label2: str = None): |
| 16 | + self.adjacency_list[label1].append(label2) |
| 17 | + self.adjacency_list[label2].append(label1) |
| 18 | + |
| 19 | + def is_bipartite(self) -> bool: |
| 20 | + for vertex in self.vertices: |
| 21 | + if self.color[vertex] is not None: |
22 | 22 | continue |
23 | | - self._colors[vertex] = "red" |
24 | 23 | q: Queue = Queue() |
| 24 | + self.color[vertex] = "red" |
25 | 25 | q.enqueue(vertex) |
26 | 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]: |
| 27 | + tmp: str = q.dequeue() |
| 28 | + for neighbour in self.adjacency_list[tmp]: |
| 29 | + if self.color[neighbour] == self.color[tmp]: |
30 | 30 | return False |
31 | | - if self._colors[neighbour] is None: |
32 | | - if self._colors[v] == "red": |
33 | | - self._colors[neighbour] = "blue" |
| 31 | + if self.color[neighbour] is None: |
| 32 | + if self.color[tmp] == "red": |
| 33 | + self.color[neighbour] = "blue" |
34 | 34 | else: |
35 | | - self._colors[neighbour] = "red" |
| 35 | + self.color[neighbour] = "red" |
36 | 36 | q.enqueue(neighbour) |
37 | 37 | return True |
38 | 38 |
|
39 | 39 |
|
40 | 40 |
|
41 | 41 |
|
42 | 42 |
|
| 43 | + |
0 commit comments