Download Data Structures & Algorithms (DSA) — Graph Algorithms Cheat Sheet & Python Code Templates and more Study Guides, Projects, Research Data Structures and Algorithms in PDF only on Docsity!
GRAPH ALGORITHMS
BFS • DFS • DIJKSTRA • TOPOLOGICAL SORT
Study Guide & Reference Manual
Data Structures & Algorithms • Python 3
CS 201 / DSA Students • Technical Interview Candidates
Visual explanations, implementation templates, complexity analysis, and exam warnings.
Document Layout Guide
This document is formatted for Microsoft Word and Google Docs. Code is presented in a
monospace style with light-grey shading. Exam warnings and complexity insights use
highlighted callout boxes.
Quick-Reference Big-O Complexity Chart
Algorithm Adjacency List Adjacency
Matrix
Space Primary Use
Case
BFS O(V + E) O(V²) O(V) Shortest path on
unweighted
graphs, level-
order traversal
DFS O(V + E) O(V²) O(V) Pathfinding,
cycle detection,
maze solving,
topological
foundations
Dijkstra O((V + E) log V) O(V²) O(V) Shortest path on
weighted graphs
(non-negative
weights)
Topological Sort O(V + E) O(V²) O(V) Scheduling task
dependencies,
build system
ordering
Note: V represents the total number of vertices (nodes), and E represents the total number of
edges.
Table of Contents
1. Graph Representations: Adjacency List vs. Matrix
2. Breadth-First Search (BFS)
• Core Mechanism & FIFO Queue Logic
• Custom Python Implementation
• Step-by-Step Traversal Trace
3. Depth-First Search (DFS)
• Call Stack Mechanics & Backtracking
• Custom Python Implementation
• Cycle Detection Subroutine
4. Dijkstra’s Shortest Path Algorithm
• Greedy Strategy & Priority Queue Operations
• Custom Python Implementation (Min-Heap)
• Edge Relaxation Visual Trace
5. Topological Sort (Kahn’s Algorithm)
• Dependency Graphs & In-Degree Resolution
• Custom Python Implementation
6. Common Bugs, Pitfalls & Exam Warnings
1. Graph Representations
Before executing traversals, graphs must be stored efficiently in memory.
Adjacency List
Maps each node to a list of its connected neighbours. Optimal for sparse graphs (E ≪ V²).
Adjacency List representation of an unweighted graph
network_graph = { 'A': ['B', 'C'], 'B': ['A', 'D', 'E'], 'C': ['A', 'F'], 'D': ['B'], 'E': ['B', 'F'], 'F': ['C', 'E'] }
2. Breadth-First Search (BFS) Conceptual Mechanics
Step 3: Pop 'Gamma' -> Check 'Zeta' Queue = ['Delta', 'Epsilon', 'Zeta']
TIME COMPLEXITY INSIGHT
BFS guarantees the shortest path in unweighted graphs because it processes nodes in strict
order of their distance from the source node. Each vertex enters the queue once, yielding O(V
+ E) overall complexity.
3. Depth-First Search (DFS) Conceptual Mechanics
DFS explores as deeply down a path as possible before backtracking. It uses a Last-In, First-Out
(LIFO) Stack, either explicitly via a data structure or implicitly using function call stacks.
Custom Problem Scenario
Detect if a cyclic dependency exists within a software deployment graph, where nodes
represent modules and directed edges represent explicit compilation dependencies.
Python Implementation def check_compilation_cycles(dependency_graph): """ Detects cycles in a Directed Graph using 3-state tracking with DFS recursion. States: 0 = Unvisited, 1 = Visiting (In Current Call Stack), 2 = Completely Processed """ node_state = {node: 0 for node in dependency_graph} def dfs_cycle_search(current_node): node_state[current_node] = 1 for neighbor in dependency_graph.get(current_node, []): if node_state[neighbor] == 1: return True if node_state[neighbor] == 0: if dfs_cycle_search(neighbor): return True node_state[current_node] = 2 return False for node in dependency_graph: if node_state[node] == 0: if dfs_cycle_search(node): return True return False
Example: Module Dependencies with a Cycle (Auth -> Database -> Cache -> Auth)
modules = { 'Auth': ['Database'], 'Database': ['Cache'], 'Cache': ['Auth', 'Logger'], 'Logger': [] } print("Cycle Detected:", check_compilation_cycles(modules))
EXAM WARNING
When implementing DFS recursively, ensure your base cases or visit markers prevent stack
overflow exceptions caused by circular references.
4. Dijkstra’s Shortest Path Algorithm Conceptual Mechanics
Dijkstra calculates the shortest path from a starting node to all other nodes on a weighted graph
with non-negative edge costs. It maintains a tentative distance table and continuously selects
the unvisited node with the smallest distance using a Min-Priority Queue (Min-Heap).
Custom Problem Scenario
A logistics pipeline must find the cheapest toll route to transfer goods between cargo hubs over
a road network with distinct toll fees.
Python Implementation import heapq def calculate_cheapest_freight_routes(road_network, start_hub): """ Calculates shortest paths using Dijkstra's Algorithm with a Priority Queue. road_network expected format: { node: [(neighbor, cost), ...] } """ cheapest_cost = {hub: float('inf') for hub in road_network} cheapest_cost[start_hub] = 0 priority_heap = [(0, start_hub)] while priority_heap: accumulated_cost, current_hub = heapq.heappop(priority_heap) if accumulated_cost > cheapest_cost[current_hub]: continue for adjacent_hub, toll_cost in road_network.get(current_hub, []): new_path_cost = accumulated_cost + toll_cost if new_path_cost < cheapest_cost[adjacent_hub]: cheapest_cost[adjacent_hub] = new_path_cost heapq.heappush(priority_heap, (new_path_cost, adjacent_hub))
Computes a valid course sequence using Kahn's Algorithm (BFS In-Degree method). prerequisites = [(course, required_prerequisite), ...] """ in_degree = {i: 0 for i in range(total_courses)} adj_list = {i: [] for i in range(total_courses)} for course, prereq in prerequisites: adj_list[prereq].append(course) in_degree[course] += 1 zero_prereq_queue = deque( [c for c in in_degree if in_degree[c] == 0] ) ordered_schedule = [] while zero_prereq_queue: current_course = zero_prereq_queue.popleft() ordered_schedule.append(current_course) for dependent_course in adj_list[current_course]: in_degree[dependent_course] -= 1 if in_degree[dependent_course] == 0: zero_prereq_queue.append(dependent_course) if len(ordered_schedule) == total_courses: return ordered_schedule else: return []
Example: 4 Courses (0, 1, 2, 3)
Course 1 requires Course 0
Course 2 requires Course 0
Course 3 requires Courses 1 and 2
prereq_list = [(1, 0), (2, 0), (3, 1), (3, 2)] print("Valid Execution Sequence:", resolve_course_prerequisites(4, prereq_list))
6. Common Bugs, Pitfalls & Exam Warnings
EXAM WARNING
1. BFS vs DFS for Pathfinding:
- Use BFS for unweighted graphs when you need a guaranteed shortest path.
- DFS can find a path, but it does not generally guarantee the shortest path.
2. Infinite Recursion Traps:
- Always update the visited/state marker before recursively exploring a node.
- Marking too late can allow duplicate visits or recursion problems.
3. Topological Sort Scope:
- Topological sorting is valid for Directed Acyclic Graphs (DAGs).
- If the graph contains a directed cycle, a complete topological ordering cannot be produced.
- Topological ordering is defined for directed graphs, not general undirected graphs. Final Revision Checklist
BFS → FIFO queue → shortest paths in unweighted graphs.
DFS → LIFO stack/call stack → deep exploration, backtracking, and cycle detection.
Dijkstra → min-heap → weighted shortest paths with non-negative edge weights.
Kahn’s Algorithm → in-degree + queue → topological ordering of DAGs.
Always identify V (vertices) and E (edges) before stating graph complexity.
Check whether the graph is directed/undirected, weighted/unweighted, and cyclic/acyclic
before choosing an algorithm.
End of Module • Graph Algorithms Reference Manual