DSA · Beginner · Pattern 4 of 11
Matrix (2-D Arrays)
10 problems.
Your progress0%
- 1st Visit
- 0/10
- 2nd Visit
- 0/10
- Revise
- 0/10
About this pattern
A matrix is a 2-D array indexed by row and column; visiting all m * n cells costs O(m * n). Most problems combine a few moves: scanning rows or columns, walking the diagonals (i == j and i + j == n - 1), peeling the grid layer by layer, checking a cell's four neighbours with direction arrays, and transforming in place by swapping mirrored cells.
Recognise the pattern when the input is a grid, board or table, or when the statement mentions rows, columns, diagonals, rotation or spirals. Grids need not be square, so keep m and n separate and check both bounds before reading a neighbour.
// Row-major traversal of an m x n grid.
for (int r = 0; r < m; ++r)
for (int c = 0; c < n; ++c)
visit(grid[r][c]);
// Four side neighbours of (r, c), skipping cells outside the grid.
int dr[4] = {-1, 1, 0, 0}, dc[4] = {0, 0, -1, 1};
for (int k = 0; k < 4; ++k) {
int nr = r + dr[k], nc = c + dc[k];
if (nr < 0 || nr >= m || nc < 0 || nc >= n) continue;
visit(grid[nr][nc]);
}
// Flattened index: cell (r, c) <-> r * n + c.
Problems
| # | Problem | Platform | Difficulty | Open | 1st1st Visit | 2nd2nd Visit | RevRevise |
|---|---|---|---|---|---|---|---|
| 1 | Matrix Diagonal Sum | LeetCode | Easy | Solve Matrix Diagonal Sum on LeetCode (opens in a new tab) | |||
| 2 | Beautiful Matrix | Codeforces | Easy 800 | Solve Beautiful Matrix on Codeforces (opens in a new tab) | |||
| 3 | Transpose Matrix | LeetCode | Easy | Solve Transpose Matrix on LeetCode (opens in a new tab) | |||
| 4 | Target Practice | Codeforces | Easy 800 | Solve Target Practice on Codeforces (opens in a new tab) | |||
| 5 | Pascal's Triangle | LeetCode | Easy | Solve Pascal's Triangle on LeetCode (opens in a new tab) | |||
| 6 | Lights Out | Codeforces | Easy 900 | Solve Lights Out on Codeforces (opens in a new tab) | |||
| 7 | Set Matrix Zeroes | LeetCode | Medium | Solve Set Matrix Zeroes on LeetCode (opens in a new tab) | |||
| 8 | Valid Sudoku | LeetCode | Medium | Solve Valid Sudoku on LeetCode (opens in a new tab) | |||
| 9 | Rotate Image | LeetCode | Medium | Solve Rotate Image on LeetCode (opens in a new tab) | |||
| 10 | Spiral Matrix | LeetCode | Medium | Solve Spiral Matrix on LeetCode (opens in a new tab) |