What is a graph?#
A graph is a set of vertices (nodes) connected by edges. Graphs model anything with connections:
- Google Maps - places are vertices, roads are weighted edges (distance or time).
- Social networks - people and friendships.
- The web - pages and links (directed).
- Railways / airlines - stations and routes.
- Course prerequisites - you must finish Python before Machine Learning.
| Kind | Meaning |
|---|---|
| undirected | edges go both ways (friendship) |
| directed | edges have a direction (follows on Instagram, one-way streets) |
| weighted | edges have a cost (km, minutes, rupees) |
| cyclic / acyclic | has a loop / has no loop (a DAG - e.g. task dependencies) |
| connected | every vertex can reach every other |
Graph को शहरों और सड़कों के नक्शे की तरह समझें। शहर = vertex, सड़क = edge। अगर सड़क दोनों तरफ जाती है तो undirected, one-way हो तो directed, और सड़क की लंबाई लिखी हो तो weighted graph।
Representing a graph#
0: 1 2 1: 0 2 2: 0 1 3 3: 2 edge 1-3? 0, edge 2-3? 1
Most real graphs are sparse (few edges per vertex), so the adjacency list is the usual choice.
Breadth-First Search (BFS)#
BFS starts at a source and visits all neighbours first, then their neighbours - level by level, using a queue. In an unweighted graph it gives the shortest path (fewest edges).
BFS order: 0 1 2 3 4 5 6 Shortest 0 -> 6 uses 4 edges: 0 -> 1 -> 3 -> 5 -> 6
Depth-First Search (DFS)#
DFS goes as deep as possible along one branch, then backtracks - naturally written with recursion (the call stack).
visit 0
visit 1
visit 3
visit 4
visit 2
visit 5DFS is used for: detecting cycles, topological sort (ordering tasks with prerequisites), finding connected components, solving mazes and puzzles (backtracking).
BFS vs DFS#
| BFS | DFS | |
|---|---|---|
| data structure | queue | stack / recursion |
| order | level by level | deep first, then backtrack |
| shortest path (unweighted) | yes | no |
| memory | can be large (a whole level) | proportional to the depth |
| typical uses | shortest path, nearest X, levels | cycles, components, topological sort, mazes |
| time | O(V + E) | O(V + E) |
For weighted graphs (road distances), BFS is not enough. Dijkstra's algorithm uses a priority_queue to find shortest paths - that's what maps and delivery apps use, with heuristics like A* to search faster.
Summary#
- Graphs = vertices + edges; directed/undirected, weighted/unweighted.
- Store with an adjacency list (usual) or matrix (dense graphs, O(1) edge checks).
- BFS (queue) → shortest path by edges; DFS (recursion) → explore, components, cycles.
- Always keep
visited; both run in O(V + E).