0% found this document useful (0 votes)
1 views5 pages

1 Simplified & Detailed Summary of Depth-First Search (DFS)

Depth-First Search (DFS) is a graph traversal algorithm that explores each branch as far as possible before backtracking, commonly used in applications like maze solving and AI decision trees. It can be implemented recursively or iteratively using a stack, with time complexity O(V + E) and space complexity O(V). DFS can also detect cycles in graphs by tracking parent nodes during traversal.

Uploaded by

josh.great0508
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views5 pages

1 Simplified & Detailed Summary of Depth-First Search (DFS)

Depth-First Search (DFS) is a graph traversal algorithm that explores each branch as far as possible before backtracking, commonly used in applications like maze solving and AI decision trees. It can be implemented recursively or iteratively using a stack, with time complexity O(V + E) and space complexity O(V). DFS can also detect cycles in graphs by tracking parent nodes during traversal.

Uploaded by

josh.great0508
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

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.

How DFS Works

●​ DFS starts from a chosen node (called the root in trees).


●​ It explores each neighbor of the current node recursively before backtracking.
●​ It uses a stack (either explicitly or via recursion) to track the path.

DFS Example

Consider this undirected graph:

mathematica
CopyEdit
A
/ \
B C
/ \ \
D E F

DFS traversal from A (in lexicographical order) gives:​


A → B → D → E → C → F

Simple DFS Code (Recursive Approach)


python
CopyEdit
# Graph Representation (Adjacency List)
graph = {
'A': ['B', 'C'],
'B': ['D', 'E'],
'C': ['F'],
'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:

●​ graph: A dictionary representing the graph.


●​ dfs(node, visited): Recursively visits each node and marks it as visited.
●​ visited: A set to keep track of visited nodes.
●​ We start DFS from node 'A', and the function explores as far as possible before
backtracking.

2️⃣ More Detailed DFS Code with Explanation

Here’s a stack-based iterative approach for DFS:

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')

Explanation of Iterative DFS Code:

●​ Uses stack (LIFO) instead of recursion.


●​ Pushes the reversed neighbors so that the leftmost node is visited first.
●​ Ensures each node is visited once using a visited set.
●​ Starts from 'A' and explores as deeply as possible.

3️⃣ More Detailed Overview of DFS (Intermediate Level Explanation)

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.

Intermediate-Level DFS Code (Graph Traversal with Parent Tracking and


Cycle Detection)

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}")

for neighbor in graph[node]:


if neighbor not in visited:
if dfs_with_cycle_detection(graph, neighbor, visited,
node):
return True # Cycle found
elif neighbor != parent:
print(f"Cycle detected at {node} with {neighbor}")
return True # Cycle detected

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:

●​ Tracks Parent Node: Prevents backtracking being mistaken for a cycle.


●​ Detects Cycles: If a node is visited and is not the parent, a cycle exists.
●​ More Complex DFS Use Case: Useful in real-world graph problems like network
routing.

You might also like