-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdfs.py
More file actions
23 lines (16 loc) · 652 Bytes
/
dfs.py
File metadata and controls
23 lines (16 loc) · 652 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def dfs(visited, graph, node):
if node not in visited:
print(node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
graph_input = {}
num_edges = int(input("Enter the number of edges: "))
for _ in range(num_edges):
src_node, *adj_nodes = input("Enter source node and its adjacent nodes separated by spaces: ").split()
graph_input[src_node] = adj_nodes
start_node = input("Enter the start node for DFS traversal: ")
graph = {key: value for key, value in graph_input.items()}
visited = set()
print("Following is the Depth-First Search:")
dfs(visited, graph, start_node)