-
Python implementation of Depth-First Search (DFS) algorithm for graph traversal.
-
Breakdown of the code
-
Initialization :
-
graph: This dictionary represents the graph. Keys are nodes (vertices), and their corresponding values are lists of their adjacent nodes.
-
start_node: This variable stores the starting node for the DFS traversal.
-
visited: A set is used to keep track of nodes that have already been visited, preventing cycles.
-
stack: A list (which acts as a stack using the pop() method) is used to store nodes to be explored. Initially, it contains only the start_node.
-
DFS Traversal
-
while stack: The loop continues as long as there are nodes in the stack.
- current_node = stack.pop(): The topmost node from the stack is popped (removed) and assigned to current_node.
- current_node = stack.pop(): The topmost node from the stack is popped (removed) and assigned to current_node.
-
if current_node not in visited:
- print(current_node, end=""): If the current node has not been visited before, it is printed.
- visited.add(current_node): The current node is added to the visited set.
- print(current_node, end=""): If the current node has not been visited before, it is printed.
-
for neighbor in graph[current_node]:
- if neighbor not in visited: If a neighbor of the current node has not been visited:
- stack.append(neighbor): The neighbor is pushed (added) onto the stack for exploration later.
- stack.append(neighbor): The neighbor is pushed (added) onto the stack for exploration later.
OUTPUT: A D C G E F
- if neighbor not in visited: If a neighbor of the current node has not been visited:
Made By - SWAGNIK SHIT
Reg No. - 2301292134