๐งฉ 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!