Skip to content

Commit 3fbedbd

Browse files
committed
feat(algs): add dfs to graph class
1 parent b97c5ef commit 3fbedbd

File tree

1 file changed

+34
-4
lines changed

1 file changed

+34
-4
lines changed

algorithms/graph.py

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ class Graph:
1010
def __init__(self, adjacency_matrix, num_vertices):
1111
self.adj_mat = adjacency_matrix
1212
self.v = num_vertices
13+
self.visited = np.zeros(self.v)
14+
self.steps_taken = -1*np.ones(self.v)
15+
self.steps = 0
1316

1417
def is_adjacent(self, v1, v2):
1518
return self.adj_mat[v1, v2]
@@ -42,13 +45,40 @@ def add_edges(self, edges):
4245
j = edge[1]
4346
self.adj_mat[i][j] = self.adj_mat[j][i] = 1
4447

48+
def neighbour(self, vertex):
49+
return np.nonzero(self.adj_mat[vertex])[0]
50+
51+
def dfs(self, start):
52+
print("at vertex", start)
53+
if self.visited[start]:
54+
print("Already visited")
55+
return
56+
57+
print("mark as visited")
58+
# Mark current cell as visited
59+
self.visited[start] = True
60+
self.steps_taken[start] = self.steps
61+
self.steps += 1
62+
print(self.visited)
63+
64+
# Visit every neighbouring cell
65+
for cell in self.neighbour(start):
66+
self.dfs(cell)
67+
4568

4669

4770
# Test Graph class
4871
# t1 = Graph([[1,1,1,0],[1,1,0,0],[1,0,1,0],[0,0,0,1]], 4)
4972
# print(t1.find_num_islands())
5073

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())
74+
def test2():
75+
t2 = Graph(np.zeros((6,6)),6)
76+
edges = [[0,5],[2,4],[2,3],[3,4]]
77+
t2.add_edges(edges)
78+
print("Num islands:", t2.find_num_islands())
79+
print("Neighbours of vertex 0", t2.neighbour(0))
80+
print("Neighbours of vertex 3", t2.neighbour(3))
81+
t2.dfs(2)
82+
print(t2.steps_taken)
83+
84+
# test2()

0 commit comments

Comments
 (0)