Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

DSA
Data Structures & Algorithms
0/15 completed
Beginner
Big-O and complexityArrays and stringsHash maps and setsTwo pointers and sliding windows
Intermediate
Linked listsStacks and queuesRecursion and backtrackingSorting algorithmsBinary search
Advanced
Trees and binary search treesHeaps and priority queuesGraphs: BFS and DFSDynamic programming
Pro
Shortest paths, topological sort and union-findSolving problems in coding interviews
Tracks / Data Structures & Algorithms / Advanced

Graphs: BFS and DFS

A graph is a set of nodes (vertices) connected by edges. It's the most general data structure: road maps, social networks, the web's links, package dependencies, airline routes, and even game states are graphs. Trees are just graphs without cycles. The two fundamental ways to explore a graph are breadth-first search (BFS) and depth-first search (DFS).

Kinds of graphs

Example
Undirected: edges go both ways Friendships, roads
Directed: edges have a direction "Follows" on social media, task dependencies, links
Weighted: edges have costs Distances, prices, latencies
Cyclic / acyclic A directed acyclic graph (DAG) has no cycles: build steps, course prerequisites

Representing a graph

The usual choice is an adjacency list: each node maps to its neighbours. It uses O(V + E) memory, where V is the number of vertices and E the number of edges.

Python · editable

An adjacency matrix (matrix[a][b] = 1) answers "are a and b connected?" in O(1), but needs O(V²) memory, so it suits small, dense graphs.

Breadth-first search

BFS explores in rings: all neighbours first, then their neighbours, and so on, using a queue. Because it reaches nodes in order of distance, BFS finds the shortest path in an unweighted graph:

Python · editable

Each node and edge is processed once: O(V + E).

Depth-first search

DFS goes as deep as possible before backtracking, using recursion (or an explicit stack). It's the natural tool for exploring every reachable node, finding connected components, detecting cycles and ordering dependencies:

Python · editable
BFS DFS
Uses A queue A stack (or recursion)
Explores Level by level One path to the end, then backtracks
Shortest path (unweighted) ✔ ✖
Typical uses Shortest paths, nearest X, levels Components, cycles, topological order, mazes, backtracking
Time O(V + E) O(V + E)

Grids are graphs

Each cell is a node connected to its up/down/left/right neighbours. Counting islands (connected groups of land cells) is one of the most common interview questions:

Python · editable

And BFS on a grid finds the shortest route through a maze:

Python · editable

Cycle detection in a directed graph

In a dependency graph, a cycle means "A needs B needs C needs A": impossible to build. DFS with three colours finds it: white (unvisited), grey (on the current path), black (finished). Reaching a grey node means you've looped back:

Python · editable

Practice

  1. Is there a path between two nodes? Write it with BFS and with DFS.
  2. "Rotting oranges": in a grid, each minute rotten oranges spoil their neighbours. How many minutes until all are rotten? (Hint: BFS from all rotten oranges at once.)
  3. Clone a graph: return a deep copy of every node and edge.
✎ Check your understanding

1.Which search finds the shortest path in an unweighted graph?

2.What is the time complexity of BFS or DFS on an adjacency list?

3.In three-colour DFS cycle detection, what does reaching a grey node mean?

← Heaps and priority queues