Skip to content

Commit 885d759

Browse files
committed
feat(algs): add graph class
1 parent f829dc3 commit 885d759

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

algorithms/graph.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
Graph class
3+
4+
Jessica Yung
5+
Jan 2018
6+
"""
7+
import numpy as np
8+
9+
class Graph:
10+
def __init__(self, adjacency_matrix, num_vertices):
11+
self.adj_mat = adjacency_matrix
12+
self.v = num_vertices
13+
14+
def is_adjacent(v1, v2):
15+
return self.adj_mat[v1, v2]
16+
17+
def remove_vertex(v):
18+
self.adj_mat[v,:] = 0
19+
self.adj_mat[:,v] = 0
20+
21+
def find_num_islands(self):
22+
num_islands = 0
23+
accounted_for = np.zeros(self.v)
24+
for v in range(self.v):
25+
if accounted_for[v]:
26+
continue
27+
if not sum(self.adj_mat[v] * accounted_for):
28+
num_islands += 1
29+
# accounted_for[v] = True
30+
indices = np.nonzero(self.adj_mat[v][v:])[0] # need [0] bc else returns a tuple
31+
indices += v
32+
for index in indices:
33+
accounted_for[index] = True
34+
self.num_islands = num_islands
35+
return num_islands
36+
37+
# Test Graph class
38+
# t1 = Graph([[1,1,1,0],[1,1,0,0],[1,0,1,0],[0,0,0,1]], 4)
39+
# print(t1.find_num_islands())
40+

0 commit comments

Comments
 (0)