Skip to content

Commit d6fd306

Browse files
committed
feat(algs): add add_edges, fix remove_vertex in Graph class
- add extra test case
1 parent 885d759 commit d6fd306

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

algorithms/graph.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,13 @@ def __init__(self, adjacency_matrix, num_vertices):
1111
self.adj_mat = adjacency_matrix
1212
self.v = num_vertices
1313

14-
def is_adjacent(v1, v2):
14+
def is_adjacent(self, v1, v2):
1515
return self.adj_mat[v1, v2]
1616

17-
def remove_vertex(v):
18-
self.adj_mat[v,:] = 0
19-
self.adj_mat[:,v] = 0
17+
def remove_vertex(self, v):
18+
self.adj_mat = np.delete(self.adj_mat, v, 0)
19+
self.adj_mat = np.delete(self.adj_mat, v, 1)
20+
self.v -= 1
2021

2122
def find_num_islands(self):
2223
num_islands = 0
@@ -34,7 +35,20 @@ def find_num_islands(self):
3435
self.num_islands = num_islands
3536
return num_islands
3637

38+
def add_edges(self, edges):
39+
"""Edges = an array of length-two arrays, each length-two array representing an edge."""
40+
for edge in edges:
41+
i = edge[0]
42+
j = edge[1]
43+
self.adj_mat[i][j] = self.adj_mat[j][i] = 1
44+
45+
46+
3747
# Test Graph class
3848
# t1 = Graph([[1,1,1,0],[1,1,0,0],[1,0,1,0],[0,0,0,1]], 4)
3949
# print(t1.find_num_islands())
4050

51+
# t2 = Graph(np.zeros((6,6)),6)
52+
# edges = [[0,5],[2,4],[2,3],[3,4]]
53+
# t2.add_edges(edges)
54+
# print(t2.find_num_islands())

0 commit comments

Comments
 (0)