Skip to main content

Longest Increasing Path in a Matrix

LeetCode 329 | Difficulty: Hard​

Hard

Problem Description​

Given an m x n integers matrix, return the length of the longest increasing path in matrix.

From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary (i.e., wrap-around is not allowed).

Example 1:

Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
Explanation: The longest increasing path is [1, 2, 6, 9].

Example 2:

Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
Output: 4
Explanation: The longest increasing path is [3, 4, 5, 6]. Moving diagonally is not allowed.

Example 3:

Input: matrix = [[1]]
Output: 1

Constraints:

- `m == matrix.length`

- `n == matrix[i].length`

- `1 <= m, n <= 200`

- `0 <= matrix[i][j] <= 2^31 - 1`

Topics: Array, Dynamic Programming, Depth-First Search, Breadth-First Search, Graph Theory, Topological Sort, Memoization, Matrix


Approach​

Dynamic Programming​

Break the problem into overlapping subproblems. Define a state (what information do you need?), a recurrence (how does state[i] depend on smaller states?), and a base case. Consider both top-down (memoization) and bottom-up (tabulation) approaches.

When to use

Optimal substructure + overlapping subproblems (counting ways, min/max cost, feasibility).

BFS (Graph/Matrix)​

Use a queue to explore nodes level by level. Start from source node(s), visit all neighbors before moving to the next level. BFS naturally finds shortest paths in unweighted graphs.

When to use

Shortest path in unweighted graph, level-order processing, spreading/flood fill.

Graph Traversal​

Model the problem as a graph (nodes + edges). Choose BFS for shortest path or DFS for exploring all paths. For dependency ordering, use topological sort (Kahn's BFS or DFS with finish times).

When to use

Connectivity, shortest path, cycle detection, dependency ordering.

Matrix​

Treat the matrix as a 2D grid. Common techniques: directional arrays (dx, dy) for movement, BFS/DFS for connected regions, in-place marking for visited cells, boundary traversal for spiral patterns.

When to use

Grid traversal, island problems, path finding, rotating/transforming matrices.


Solutions​

Solution 1: C# (Best: 120 ms)​

MetricValue
Runtime120 ms
Memory41.1 MB
Date2021-12-04
Solution
public class Solution {
public int LongestIncreasingPath(int[][] matrix) {
int m = matrix.GetLength(0);
int n = matrix[0].GetLength(0);

int[][] dirs = new int[][] {
new int[] {-1, 0},
new int[] {1, 0},
new int[] {0, 1},
new int[] {0, -1}
};
int[,] cache = new int[m,n];
int max = 0;

for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
max = Math.Max(max, DfsLongestIncreasing(matrix, i, j, m, n, dirs, cache));
}

}

return max;
}

private int DfsLongestIncreasing(int[][] matrix, int i, int j, int m, int n, int[][] dirs, int[,] cache)
{
if (cache[i, j] != 0)
{
return cache[i, j];
}

int max = 1;
foreach (var dir in dirs)
{
int x = i + dir[0], y = j + dir[1];
if (x < 0 || x >= m || y < 0 || y >= n || matrix[x][y] <= matrix[i][j]) continue;
int len = 1 + DfsLongestIncreasing(matrix, x, y, m, n, dirs, cache);
max = Math.Max(max, len);
}

cache[i, j] = max;
return max;
}

}

Complexity Analysis​

ApproachTimeSpace
DP (2D)$O(n Γ— m)$$O(n Γ— m)$
Graph BFS/DFS$O(V + E)$$O(V)$

Interview Tips​

Key Points
  • Break the problem into smaller subproblems. Communicate your approach before coding.
  • Define the DP state clearly. Ask: "What is the minimum information I need to make a decision at each step?"
  • Consider if you can reduce space by only keeping the last row/few values.
  • Ask about graph properties: directed/undirected, weighted/unweighted, cycles, connectivity.