Preview — Pro guide
You are seeing a portion of this guide. Sign in and upgrade to unlock the full article, quizzes, and interview answers.
Matrix Patterns: Spiral Traversal, Island Problems & Multi-Source BFS
Matrix problems appear at every FAANG company — spiral traversal, number of islands, rotting oranges (multi-source BFS), word search, and the 0/1 matrix distance problem. Master the two core approaches: DFS/BFS for connectivity and spread, and simulation with direction arrays for traversal order problems.
The Two Matrix Pattern Families
Matrix problems reduce to two core patterns once you recognize the underlying structure:
-
Traversal order problems (spiral matrix, rotate 90°, diagonal traversal): simulate the movement using a direction array
[(0,1),(1,0),(0,-1),(-1,0)](right, down, left, up) and boundary conditions. The key is maintaining the current direction and rotating when the boundary is hit. -
Connectivity / spread problems (number of islands, rotting oranges, flood fill, 0/1 matrix): model as a graph where cells are nodes and adjacent cells (4-directional or 8-directional) are edges. Run BFS for "spread" problems (shortest distance, simultaneous spread) or DFS for "count connected components" problems.
Signal words: "island," "connected," "flood," "rotting," "spread," "spiral," "diagonal," "distance to nearest 0."