1 Simplified & Detailed Summary of Depth-First Search (DFS)
1 Simplified & Detailed Summary of Depth-First Search (DFS)
Depth-First Search (DFS) is a graph traversal algorithm that explores as far as possible along
each branch before backtracking. It is commonly used in various applications such as maze
solving, pathfinding, and AI decision trees.
DFS Example
mathematica
CopyEdit
A
/ \
B C
/ \ \
D E F
# DFS Function
def dfs(node, visited):
if node not in visited:
print(node, end=' ') # Visit node
visited.add(node)
for neighbor in graph[node]: # Explore each neighbor
dfs(neighbor, visited)
# Call DFS
visited_nodes = set()
dfs('A', visited_nodes)
Explanation of Code:
python
CopyEdit
def dfs_iterative(graph, start):
visited = set()
stack = [start]
while stack:
node = stack.pop() # Remove the last inserted element (LIFO)
if node not in visited:
print(node, end=" ")
visited.add(node)
stack.extend(reversed(graph[node])) # Push unvisited
neighbors
# Example Graph
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'D': [],
'E': [],
'F': []
}
dfs_iterative(graph, 'A')
DFS Characteristics
● Time Complexity:
○ O(V + E), where V is vertices and E is edges (graph represented as adjacency
list).
● Space Complexity:
○ O(V) in worst case due to recursion depth or explicit stack storage.
● Applications of DFS:
○ Finding paths in a maze.
○ Topological sorting.
○ Detecting cycles in graphs.
○ Solving puzzles like Sudoku.
This version keeps track of parent nodes and detects cycles in an undirected graph.
python
CopyEdit
def dfs_with_cycle_detection(graph, node, visited, parent):
visited.add(node)
print(f"Visiting: {node}")
return False
# Graph Representation
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B'],
'F': ['C']
}
visited_nodes = set()
has_cycle = dfs_with_cycle_detection(graph, 'A', visited_nodes, None)
if has_cycle:
print("Graph contains a cycle.")
else:
print("Graph does not contain a cycle.")
Explanation: