⚡0 XP🔥0

Graphs - BFS and DFS

Lesson 7 of 7 ⏱ 5 min read ✎ 2 exercises ❓ 5-question quiz ▶ Runs C++

Graph vocabulary, directed and weighted graphs, adjacency lists and matrices, breadth-first search for shortest paths, depth-first search, counting connected components, and where graphs are used in real life.

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#

▶ Try it YourselfC++
Ctrl + Enter to run
Output
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).

InteractiveBFS vs A* on a grid

Draw walls and watch BFS spread out evenly in all directions until it reaches the goal.

▶ Try it YourselfC++
Ctrl + Enter to run
Output
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).

▶ Try it YourselfC++
Ctrl + Enter to run
Output
visit 0
  visit 1
    visit 3
    visit 4
  visit 2
    visit 5

DFS 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)
Did you know?

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).

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Fewest train changes (BFS)

Cities are numbered 0-5: 0 Indore, 1 Bhopal, 2 Ujjain, 3 Dewas, 4 Gwalior, 5 Jabalpur. The direct train routes (both ways) are given as edges. Using BFS from Indore (0), print the minimum number of journeys to reach each city as Bhopal: 1. Print the cities 1 to 5 in order; print -1 for a city that can't be reached.

Bhopal: 1
Ujjain: 1
Dewas: 2
Gwalior: 2
Jabalpur: 3
Expected output:
Bhopal: 1
Ujjain: 1
Dewas: 2
Gwalior: 2
Jabalpur: 3
2

Count friend groups (DFS)

8 students (0-7) and their friendships are given. A friend group is a connected component. Use DFS to count the groups and print Groups: 3.

Expected output:
Groups: 3

Quick Quiz

Q1.

Which representation uses O(V + E) memory and suits sparse graphs?

Q2.

Which traversal finds the shortest path (fewest edges) in an unweighted graph?

Q3.

BFS uses a ___, DFS uses a ___ (or recursion).

Q4.

Why keep a visited array?

Q5.

The time complexity of BFS or DFS with an adjacency list is...