Skip to content

Commit 8d8c486

Browse files
committed
feat: Implement add_vertex and remove_vertex for AdjacencyMatrix
- Added `add_vertex` method to dynamically add vertices to the graph. - Added `remove_vertex` method to dynamically remove vertices and associated edges. - Updated adjacency matrix and edge weights accordingly. - Added test cases to verify the new functionality.
1 parent f34b7d6 commit 8d8c486

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

pydatastructs/graphs/adjacency_matrix.py

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,12 +57,30 @@ def neighbors(self, node):
5757
return neighbors
5858

5959
def add_vertex(self, node):
60-
raise NotImplementedError("Currently we allow "
61-
"adjacency matrix for static graphs only")
60+
node_name = str(node.name)
61+
if node_name in self.vertices:
62+
raise ValueError(f"Vertex {node_name} already exists in the graph.")
63+
self.vertices.append(node_name)
64+
self.__setattr__(node_name, node)
65+
self.matrix[node_name] = {}
66+
for vertex in self.vertices:
67+
self.matrix[vertex][node_name] = False
68+
self.matrix[node_name][vertex] = False
6269

6370
def remove_vertex(self, node):
64-
raise NotImplementedError("Currently we allow "
65-
"adjacency matrix for static graphs only.")
71+
node_name = str(node)
72+
if node_name not in self.vertices:
73+
raise ValueError(f"Vertex {node_name} does not exist in the graph.")
74+
self.vertices.remove(node_name)
75+
del self.matrix[node_name]
76+
for vertex in self.vertices:
77+
del self.matrix[vertex][node_name]
78+
edges_to_remove = []
79+
for edge in self.edge_weights.keys():
80+
if node_name in edge:
81+
edges_to_remove.append(edge)
82+
for edge in edges_to_remove:
83+
del self.edge_weights[edge]
6684

6785
def add_edge(self, source, target, cost=None):
6886
source, target = str(source), str(target)

pydatastructs/graphs/tests/test_adjacency_matrix.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,12 @@ def test_AdjacencyMatrix():
3030
assert raises(ValueError, lambda: g.add_edge('v', 'x'))
3131
assert raises(ValueError, lambda: g.add_edge(2, 3))
3232
assert raises(ValueError, lambda: g.add_edge(3, 2))
33+
v_3 = AdjacencyMatrixGraphNode(3, 3)
34+
g.add_vertex(v_3)
35+
assert '3' in g.vertices
36+
assert g.is_adjacent(3, 0) is False
37+
g.add_edge(3, 0, 0)
38+
assert g.is_adjacent(3, 0) is True
39+
g.remove_vertex(3)
40+
assert '3' not in g.vertices
41+
assert raises(ValueError, lambda: g.add_edge(3, 0))

0 commit comments

Comments
 (0)