|
| 1 | +from pydatastructs.graphs.graph import Graph |
| 2 | +from pydatastructs.linear_data_structures import OneDimensionalArray |
| 3 | +from pydatastructs.utils.misc_util import AdjacencyMatrixGraphNode |
| 4 | + |
| 5 | +__all__ = [ |
| 6 | + 'AdjacencyMatrix' |
| 7 | +] |
| 8 | + |
| 9 | +class AdjacencyMatrix(Graph): |
| 10 | + """ |
| 11 | + Adjacency matrix implementation of graphs. |
| 12 | +
|
| 13 | + See also |
| 14 | + ======== |
| 15 | +
|
| 16 | + pydatastructs.graphs.graph.Graph |
| 17 | + """ |
| 18 | + def __new__(cls, *vertices): |
| 19 | + obj = object.__new__(cls) |
| 20 | + num_vertices = len(vertices) |
| 21 | + obj.vertices = OneDimensionalArray( |
| 22 | + AdjacencyMatrixGraphNode, |
| 23 | + num_vertices) |
| 24 | + for vertex in vertices: |
| 25 | + obj.vertices[vertex.name] = vertex |
| 26 | + obj.matrix = OneDimensionalArray( |
| 27 | + OneDimensionalArray, |
| 28 | + num_vertices) |
| 29 | + for i in range(num_vertices): |
| 30 | + obj.matrix[i] = OneDimensionalArray( |
| 31 | + bool, |
| 32 | + num_vertices) |
| 33 | + obj.matrix[i].fill(False) |
| 34 | + return obj |
| 35 | + |
| 36 | + def is_adjacent(self, node1, node2): |
| 37 | + return self.matrix[node1][node2] |
| 38 | + |
| 39 | + def neighbors(self, node): |
| 40 | + neighbors = [] |
| 41 | + for i in range(self.matrix[node]._size): |
| 42 | + if self.matrix[node][i]: |
| 43 | + neighbors.append(self.vertices[i]) |
| 44 | + return neighbors |
| 45 | + |
| 46 | + def add_vertex(self, node): |
| 47 | + raise NotImplementedError("Currently we allow " |
| 48 | + "adjacency matrix for static graphs only") |
| 49 | + |
| 50 | + def remove_vertex(self, node): |
| 51 | + raise NotImplementedError("Currently we allow " |
| 52 | + "adjacency matrix for static graphs only.") |
| 53 | + |
| 54 | + def add_edge(self, source, target): |
| 55 | + self.matrix[source][target] = True |
| 56 | + |
| 57 | + def remove_edge(self, source, target): |
| 58 | + self.matrix[source][target] = False |
0 commit comments