Skip to content

Commit a23f804

Browse files
authored
Create dfs.py
1 parent 950de89 commit a23f804

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

Graphs/DFS/dfs.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
def dfs(node, graph, visited, component):
2+
component.append(node) # Store answer
3+
visited[node] = True # Mark visited
4+
5+
# Traverse to each adjacent node of a node
6+
for child in graph[node]:
7+
if not visited[child]: # Check whether the node is visited or not
8+
dfs(child, graph, visited, component)
9+
10+
11+
if __name__ == "__main__":
12+
13+
# Graph of nodes
14+
graph = {
15+
0: [2],
16+
1: [2, 3],
17+
2: [0, 1, 4],
18+
3: [1, 4],
19+
4: [2, 3]
20+
}
21+
node = 0 # Starting node
22+
visited = [False]*len(graph)
23+
component = []
24+
dfs(node, graph, visited, component) # Traverse to each node of a graph
25+
print(f"Following is the Depth-first search: {component}") # Print the answer

0 commit comments

Comments
 (0)