Depth-First Search
Medium

Matrices as Graphs

Treating 2D Grids as implicit graphs.
2D Grid as a Graph

Many problems involve a 2D Matrix (Grid). This is implicitly a Graph.

  • Node: Each cell (r, c) is a node.
  • Edges: Adjacent cells (Up, Down, Left, Right) are neighbors.

So a matrix of size M x N is a graph with M*N nodes.

Matrix Visualization
Step 1 / 8
(0,0)
(0,1)
(0,2)
(1,0)
(1,1)
(1,2)
(2,0)
(2,1)
(2,2)

Welcome! A Matrix is essentially a grid-shaped Graph. Each cell `(row, col)` is a **Node**.

1x
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.
Unlock VisualizerPREMIUM FEATURE
DFS on a Grid (Flood Fill)

DFS on a grid is often called Flood Fill.

Since we can move in 4 directions, cycles are everywhere (A -> B -> C -> D -> A). We MUST handle visited cells.

Space Optimization: Instead of a separate visited set, we can often modify the input grid itself (e.g., change '1' to '0' or '#') to mark it as visited, saving O(M*N) space.

Boundary Checks

Always check if the new coordinates are valid before accessing the matrix.

if (r < 0 || c < 0 || r >= rows || c >= cols) -> Invalid.

Stop Guessing, Start Mastering.

Build the FAANG intuition. Master this pattern with optimized implementations, visual dry runs, and our curated collection of high-yield problems.

Start Your Premium Prep