Skip to content

Commit 2ce57e2

Browse files
taseikyostokhos
authored andcommitted
Update graphs/depth_first_search_2.py (TheAlgorithms#3799)
- update naming style to snake_case - add type hints
1 parent 9a702e0 commit 2ce57e2

File tree

1 file changed

+28
-28
lines changed

1 file changed

+28
-28
lines changed

Diff for: graphs/depth_first_search_2.py

+28-28
Original file line numberDiff line numberDiff line change
@@ -8,58 +8,58 @@ def __init__(self):
88
self.vertex = {}
99

1010
# for printing the Graph vertices
11-
def printGraph(self):
11+
def print_graph(self) -> None:
1212
print(self.vertex)
13-
for i in self.vertex.keys():
13+
for i in self.vertex:
1414
print(i, " -> ", " -> ".join([str(j) for j in self.vertex[i]]))
1515

1616
# for adding the edge between two vertices
17-
def addEdge(self, fromVertex, toVertex):
17+
def add_edge(self, from_vertex: int, to_vertex: int) -> None:
1818
# check if vertex is already present,
19-
if fromVertex in self.vertex.keys():
20-
self.vertex[fromVertex].append(toVertex)
19+
if from_vertex in self.vertex:
20+
self.vertex[from_vertex].append(to_vertex)
2121
else:
2222
# else make a new vertex
23-
self.vertex[fromVertex] = [toVertex]
23+
self.vertex[from_vertex] = [to_vertex]
2424

25-
def DFS(self):
25+
def dfs(self) -> None:
2626
# visited array for storing already visited nodes
2727
visited = [False] * len(self.vertex)
2828

2929
# call the recursive helper function
3030
for i in range(len(self.vertex)):
31-
if visited[i] is False:
32-
self.DFSRec(i, visited)
31+
if not visited[i]:
32+
self.dfs_recursive(i, visited)
3333

34-
def DFSRec(self, startVertex, visited):
34+
def dfs_recursive(self, start_vertex: int, visited: list) -> None:
3535
# mark start vertex as visited
36-
visited[startVertex] = True
36+
visited[start_vertex] = True
3737

38-
print(startVertex, end=" ")
38+
print(start_vertex, end=" ")
3939

4040
# Recur for all the vertices that are adjacent to this node
41-
for i in self.vertex.keys():
42-
if visited[i] is False:
43-
self.DFSRec(i, visited)
41+
for i in self.vertex:
42+
if not visited[i]:
43+
self.dfs_recursive(i, visited)
4444

4545

4646
if __name__ == "__main__":
4747
g = Graph()
48-
g.addEdge(0, 1)
49-
g.addEdge(0, 2)
50-
g.addEdge(1, 2)
51-
g.addEdge(2, 0)
52-
g.addEdge(2, 3)
53-
g.addEdge(3, 3)
48+
g.add_edge(0, 1)
49+
g.add_edge(0, 2)
50+
g.add_edge(1, 2)
51+
g.add_edge(2, 0)
52+
g.add_edge(2, 3)
53+
g.add_edge(3, 3)
5454

55-
g.printGraph()
55+
g.print_graph()
5656
print("DFS:")
57-
g.DFS()
57+
g.dfs()
5858

5959
# OUTPUT:
60-
# 0  ->  1 -> 2
61-
# 1  ->  2
62-
# 2  ->  0 -> 3
63-
# 3  ->  3
60+
# 0 -> 1 -> 2
61+
# 1 -> 2
62+
# 2 -> 0 -> 3
63+
# 3 -> 3
6464
# DFS:
65-
#  0 1 2 3
65+
# 0 1 2 3

0 commit comments

Comments
 (0)