π What I Learned About Graphs Today

π What is a Graph?
A graph is a collection of:
Vertices (nodes): The entities (e.g., cities, people).
Edges: Connections between them (e.g., roads, friendships).
π Graph Representations
There are two common ways to represent graphs in code:
1. Adjacency Matrix
A 2D array where
matrix[i][j]
is1
if there's an edge from nodei
toj
, else0
.Great for dense graphs.
Example for a graph with 3 nodes:
0 -- 1
\
2
Adjacency Matrix:
[
[0, 1, 1],
[1, 0, 0],
[1, 0, 0]
]
2. Adjacency List
A dictionary where each key is a node and the value is a list of its neighbors.
Better for sparse graphs.
Example:
graph = {
0: [1, 2],
1: [0],
2: [0]
}
π§ Types of Graphs
Directed vs. Undirected: Edges have direction or not.
Weighted vs. Unweighted: Edges may have weights (e.g., distance).
Cyclic vs. Acyclic: Whether you can form a loop.
Connected vs. Disconnected: Whether all nodes are reachable from each other.
πΆββοΈ Graph Traversal
How do we move through a graph? Two popular methods:
π 1. DFS (Depth-First Search)
Goes deep into the graph before backtracking.
Implemented using stack or recursion.
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
print(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
dfs(graph, 0)
π 2. BFS (Breadth-First Search)
Explores all neighbors before going deeper.
Implemented using a queue.
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
node = queue.popleft()
print(node)
for neighbor in graph[node]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
bfs(graph, 0)
π§ Summary
Concept | Summary |
Adjacency Matrix | 2D grid, good for dense graphs |
Adjacency List | Dict of neighbors, good for sparse graphs |
DFS | Depth-first, uses recursion/stack |
BFS | Level-order, uses queue |
Types of Graphs | Directed, Undirected, Weighted, Cyclic, Connected |
Subscribe to my newsletter
Read articles from kasumbi phil directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
