Skip to main content

Preview — Pro guide

You are seeing a portion of this guide. Sign in and upgrade to unlock the full article, quizzes, and interview answers.

DSA·Intermediate

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.

30 min read 2 sections 1 interview questions
MatrixGridBFSDFSIslandSpiralMulti-Source BFSFlood FillDirection ArrayRotting OrangesWord Search0-1 MatrixRow Column TraversalLeetCode Medium

The Two Matrix Pattern Families

Matrix problems reduce to two core patterns once you recognize the underlying structure:

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

  2. 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."

IMPORTANT

Premium content locked

This guide is premium content. Upgrade to Pro to unlock the full guide, quizzes, and interview Q&A.