We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 950de89 commit a23f804Copy full SHA for a23f804
Graphs/DFS/dfs.py
@@ -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