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
Welcome! A Matrix is essentially a grid-shaped Graph. Each cell `(row, col)` is a **Node**.
See the Logic in Motion
Stop memorizing code. Unlock the full interactive visualizer to master the logic step-by-step.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.
- 2D Grid as a Graph
- Matrix Visualization
- The Directions Array
- DFS on a Grid (Flood Fill)
- Boundary Checks
- Dry Run (DFS Traversal)
- Edge Cases & Common Mistakes
- Complexity Analysis
- Summary
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.
