π§© Python DSA Patterns β Graph Basics πΈοΈ
Posted on: November 7, 2025
Description:
A Graph is a non-linear data structure made of nodes (vertices) and edges (connections).
Itβs used to represent relationships, networks, or connected systems like maps, social media, or web links.
β¨ Graph Types
- Directed vs Undirected β Edges may have direction.
- Weighted vs Unweighted β Edges may have cost/weight.
- Cyclic vs Acyclic β Graph may contain cycles or not.
- Dense vs Sparse β Based on how many edges exist.
π§© Common Representations
- Adjacency List β Dictionary or list of lists (space-efficient).
- Adjacency Matrix β 2D matrix (easier to query, more space).
Example adjacency list representation:
graph = {
'A': ['B', 'C'],
'B': ['A', 'D', 'E'],
'C': ['A', 'F'],
'D': ['B'],
'E': ['B', 'F'],
'F': ['C', 'E']
}
β‘ Breadth-First Search (BFS)
BFS explores all neighbors first before moving to the next level β itβs like expanding outward layer by layer.
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
node = queue.popleft()
if node not in visited:
print(node, end=" ")
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
queue.append(neighbor)
bfs(graph, 'A') # Output: A B C D E F
π‘ BFS is ideal for:
- Finding shortest paths in unweighted graphs.
- Level-order traversal (like in trees).
- Problems like βminimum stepsβ or βdegrees of connectionβ.
βοΈ Depth-First Search (DFS)
DFS dives as deep as possible before backtracking β perfect for exploring full paths or components.
def dfs(graph, node, visited=None):
if visited is None:
visited = set()
print(node, end=" ")
visited.add(node)
for neighbor in graph[node]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
dfs(graph, 'A') # Output: A B D E F C
π‘ DFS is ideal for:
- Pathfinding (exploring all possibilities).
- Cycle detection and connected components.
- Recursive backtracking (e.g., mazes, puzzles).
π§ Where It Helps
- π Network traversal & shortest path algorithms (BFS).
- π Cycle detection & connected components (DFS).
- π§ Maze and pathfinding problems.
- π Web crawling and dependency graphs.
- π§© Building recommendation systems or analyzing relationships.
β Takeaways
- BFS β Queue-based β Layer-by-layer exploration.
- DFS β Stack/Recursion β Deep exploration before backtracking.
- Core foundations for advanced topics like:
- Dijkstraβs Algorithm
- Topological Sorting
- Connected Components
- Minimum Spanning Trees
ποΈ Practice Problems
- BFS and DFS Traversal of a Graph
- Count Connected Components
- Detect Cycle in Undirected / Directed Graph
- Clone Graph
- Shortest Path in Unweighted Graph
Link copied!
Comments
Add Your Comment
Comment Added!
No comments yet. Be the first to comment!