Graphs — Representation, BFS, DFS
network, road, dependency — সবই graph
1. Graphs Are Everywhere
Social network, road map, web pages, dependency — vertex (জিনিস) + edge (সম্পর্ক) থাকলেই graph।
2. Two Representations
Adjacency Matrix
int adj[V][V];
adj[u][v] = 1; // u→v
O(V²) space; O(1) edge-check; dense graph-এ ভালো।
Adjacency List
Node *adj[V];
// linked list of neighbors
O(V+E) space; O(deg v) neighbors; sparse graph-এ preferred।
3. BFS — Breadth-First Search
#include <stdio.h>
#include <string.h>
#define V 6
int adj[V][V]; // adjacency matrix
void add_edge(int u, int v) { adj[u][v] = adj[v][u] = 1; }
void bfs(int start) {
int visited[V] = {0};
int q[V], head = 0, tail = 0;
q[tail++] = start;
visited[start] = 1;
while (head < tail) {
int u = q[head++];
printf("%d ", u);
for (int v = 0; v < V; v++)
if (adj[u][v] && !visited[v]) {
visited[v] = 1;
q[tail++] = v;
}
}
putchar('\n');
}
int main(void) {
add_edge(0,1); add_edge(0,2);
add_edge(1,3); add_edge(2,4);
add_edge(3,5); add_edge(4,5);
printf("BFS from 0: ");
bfs(0);
return 0;
}
BFS unweighted graph-এ shortest path দেয় (edges গোনার দিক থেকে)। Queue-ই মূল hardware।
4. DFS — Depth-First Search
#include <stdio.h>
#define V 6
int adj[V][V];
int visited[V];
void add_edge(int u, int v) { adj[u][v] = adj[v][u] = 1; }
void dfs(int u) {
visited[u] = 1;
printf("%d ", u);
for (int v = 0; v < V; v++)
if (adj[u][v] && !visited[v]) dfs(v);
}
int main(void) {
add_edge(0,1); add_edge(0,2);
add_edge(1,3); add_edge(2,4);
add_edge(3,5); add_edge(4,5);
printf("DFS from 0: ");
dfs(0);
putchar('\n');
return 0;
}
Recursion stack = DFS stack। Iterative version-এ নিজে stack maintain করা যায়।
5. Key Algorithms to Know
- Connected components — প্রতিটি unvisited vertex থেকে DFS।
- Cycle detection — DFS recursion stack।
- Topological sort — DFS post-order (DAG-এ)।
- Unweighted shortest path — BFS।
- Weighted (non-negative) — Dijkstra।
- General weighted — Bellman-Ford।
- MST — Kruskal / Prim।
6. Practice Problems
- Build an adjacency-list graph.Adjacency list দিয়ে graph।
✨ Show Answer
typedef struct N { int v; struct N *next; } N; N *adj[V]; void add(int u, int v) { N *n = malloc(sizeof *n); n->v = v; n->next = adj[u]; adj[u] = n; } - BFS from a source.Source থেকে BFS।
✨ Show Answer
Section 3-এর
bfs.c-ই উত্তর। - DFS recursive & iterative.DFS — recursive ও iterative।
✨ Show Answer
Recursive Section 4। Iterative: stack ব্যবহার করুন — push(start), loop: pop → visit → push all unvisited neighbors।
- Count connected components.Connected component গুনুন।
✨ Show Answer
প্রতিটি unvisited vertex থেকে DFS চালান, counter বাড়ান — total component count।
- Detect a cycle in an undirected graph.Undirected graph-এ cycle detect।
✨ Show Answer
DFS-এ parent track করুন। Neighbor visited + parent না হলে cycle।
- Detect a cycle in a directed graph.Directed graph-এ cycle।
✨ Show Answer
Three-color DFS: WHITE (unvisited), GRAY (in-progress), BLACK (done)। GRAY-এ ফেরত এলে cycle।
- Topological sort of a DAG.DAG-এর topological sort।
✨ Show Answer
DFS post-order-এ stack-এ push; শেষে stack reverse-ই topological order।
- Unweighted shortest path (BFS).Unweighted shortest path।
✨ Show Answer
BFS-এ
dist[v] = dist[u] + 1set করুন; target-এ পৌঁছালে return। - Maze / grid shortest path (2D BFS).Grid-এ shortest path।
✨ Show Answer
Queue-এ
(r, c)push। চারটি dr/dc neighbors দেখুন — bounds + visited + cell-ok চেক। - Island count in a 2D grid.2D grid-এ island সংখ্যা।
✨ Show Answer
প্রতিটি '1' cell থেকে DFS/BFS; counter বাড়ান; visited চিহ্নিত করুন।
- Flood fill.Flood fill।
✨ Show Answer
DFS recursion: current cell-এর color পরিবর্তন করুন এবং চার দিকে recurse (source color match-এ)।
- Bipartite check via 2-coloring BFS.BFS দিয়ে bipartite check।
✨ Show Answer
Source-কে color 0 দিন; BFS-এ প্রতিটি neighbor-কে opposite color। Conflict হলে not bipartite।
- Dijkstra with priority queue.Dijkstra — priority queue।
✨ Show Answer
Min-heap-এ
(dist, vertex)। Pop; relax edges; updated হলে push। O((V+E) log V)। - Bellman-Ford with negative edges.Bellman-Ford।
✨ Show Answer
V−1 বার সব edge relax। V-th iteration-এ update হলে negative cycle। O(VE)।
- Floyd-Warshall all-pairs shortest paths.Floyd-Warshall।
✨ Show Answer
Triple loop:
for k for i for j: d[i][j] = min(d[i][j], d[i][k] + d[k][j]);— O(V³)। - Kruskal MST with union-find.Kruskal MST।
✨ Show Answer
Edges sort করুন weight-এ; union-find ব্যবহার করে একটি একটি edge যোগ করুন — cycle না হলে।
- Prim MST with priority queue.Prim MST।
✨ Show Answer
Min-heap-এ
(cost, vertex)। Extract-min; unvisited হলে include; তার edges push। - Number of paths from A to B in a DAG.DAG-এ A থেকে B পর্যন্ত path সংখ্যা।
✨ Show Answer
Topological order-এ
paths[B] += paths[u], যেখানেu → B। DP। - Longest path in a DAG.DAG-এ longest path।
✨ Show Answer
Topological order-এ DP:
dist[v] = max(dist[v], dist[u] + w(u,v))। - Strongly connected components (Kosaraju).SCC — Kosaraju।
✨ Show Answer
(1) DFS finish order stack-এ রাখুন। (2) Graph reverse। (3) Reversed graph-এ stack order থেকে DFS — প্রতিটি DFS-tree একটি SCC।
- Articulation points and bridges.Articulation points ও bridges।
✨ Show Answer
DFS-এ
disc[]ওlow[]maintain করুন। Node u-এর কোনো child v-এরlow[v] >= disc[u]মানে u articulation point;low[v] > disc[u]মানে edge u-v bridge। - Word ladder (BFS over edit graph).Word ladder — BFS।
✨ Show Answer
Vertex = word; edge = এক-অক্ষর পার্থক্য। BFS দিয়ে shortest transformation।
- Knight's shortest path on a chessboard.দাবার ঘোড়ার shortest path।
✨ Show Answer
8-move BFS on 8×8 grid; visited[8][8]। Queue-এ
(r, c, dist)। - A* search intuition — what heuristic makes it consistent?A*-এর heuristic কখন consistent?
✨ Show Answer
Consistent (monotone): সকল edge (u, v)-র জন্য
h(u) ≤ c(u,v) + h(v)। গ্রিডে Manhattan বা Euclidean distance consistent। এই condition-এ একবার close-list-এ গেলে আর re-open লাগে না। - Why is almost every interesting CS problem really a graph problem in disguise?CS-এর প্রায় সব সমস্যা কেন graph-এর সমস্যা?
✨ Show Answer
যেকোনো "state → state" transition mental model-ই একটি graph — state হলো vertex, legal move হলো edge। Dijkstra, BFS, DFS, topo sort — এই সামান্য primitive দিয়েই অজস্র সমস্যা সমাধান সম্ভব।
Glossary (শব্দকোষ)
| Term | Meaning | বাংলায় |
|---|---|---|
| Graph | A collection of vertices connected by edges. | Vertex ও edge দিয়ে গঠিত structure। |
| Vertex (Node) | A point in the graph. | Graph-এর একটি বিন্দু। |
| Edge | A connection between two vertices. | দুই vertex-এর মধ্যে সংযোগ। |
| Directed Graph | Edges have direction (one-way). | Edge-এর নির্দিষ্ট দিক আছে। |
| Undirected Graph | Edges have no direction. | Edge-এর দিক নেই। |
| Weighted Graph | Edges carry numeric weights. | Edge-এ সংখ্যাগত ওজন। |
| Adjacency Matrix | 2D array where A[i][j] means edge i→j. | 2D array — A[i][j] মানে i→j edge। |
| Adjacency List | Each vertex stores its list of neighbors. | প্রতি vertex তার neighbor-list রাখে। |
| BFS | Breadth-First Search — explore neighbors level by level using a queue. | Queue দিয়ে level ধরে ধরে অনুসন্ধান। |
| DFS | Depth-First Search — go as deep as possible using recursion or a stack. | Recursion/stack দিয়ে যত গভীরে সম্ভব যাওয়া। |
| Connected Component | A maximal set of mutually reachable vertices. | পরস্পর-পৌঁছনো-যোগ্য vertex-এর সর্বোচ্চ set। |
| Cycle | A path that returns to its starting vertex. | শুরুতে ফিরে আসা path। |
| Topological Sort | Linear ordering of a DAG respecting edges. | DAG-এর edge মেনে linear ক্রম। |
| Shortest Path | Path with minimum total edge weight or count. | সর্বনিম্ন ওজন বা edge-সংখ্যার path। |
Summary — Module 29
Graph = vertices + edges। Dense-এ matrix, sparse-এ list। BFS unweighted shortest path; DFS connectivity, cycle, topological sort। প্রায় সব interesting CS problem graph-এর ছদ্মবেশ।