Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Longest Increasing Path in a Matrix in Python
Given a matrix, we need to find the length of the longest increasing path. From each cell, we can move in four directions − left, right, up, or down. We cannot move diagonally or outside the matrix boundaries.
This problem can be solved efficiently using dynamic programming with memoization and depth-first search (DFS).
Problem Example
Consider this matrix ?
| 9 | 9 | 4 |
| 6 | 6 | 8 |
| 2 | 1 | 1 |
The longest increasing path is 1 ? 6 ? 8 ? 9 with length 4.
Algorithm Approach
We use DFS with memoization to avoid recomputing paths from the same cell ?
- For each cell, explore all four adjacent cells
- Move only to cells with greater values
- Use memoization to store the longest path from each cell
- Return the maximum path length found
Implementation
class Solution:
def longestIncreasingPath(self, matrix):
if not matrix or not matrix[0]:
return 0
rows, cols = len(matrix), len(matrix[0])
# Memoization table
dp = [[0] * cols for _ in range(rows)]
def dfs(i, j):
# If already computed, return cached result
if dp[i][j] != 0:
return dp[i][j]
# Base case: current cell contributes length 1
dp[i][j] = 1
# Four directions: up, down, left, right
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for di, dj in directions:
ni, nj = i + di, j + dj
# Check bounds and increasing condition
if (0 <= ni < rows and 0 <= nj < cols and
matrix[ni][nj] > matrix[i][j]):
dp[i][j] = max(dp[i][j], 1 + dfs(ni, nj))
return dp[i][j]
max_length = 0
# Try starting from every cell
for i in range(rows):
for j in range(cols):
max_length = max(max_length, dfs(i, j))
return max_length
# Test the solution
solution = Solution()
matrix = [[9, 9, 4], [6, 6, 8], [2, 1, 1]]
result = solution.longestIncreasingPath(matrix)
print(f"Longest increasing path length: {result}")
Longest increasing path length: 4
How It Works
The algorithm works as follows ?
- DFS Function: For each cell, recursively explore valid neighboring cells
-
Memoization: Store computed results in
dptable to avoid redundant calculations - Direction Check: Only move to adjacent cells (not diagonal) with greater values
- Path Length: Each cell contributes 1 to the path length, plus the maximum path from valid neighbors
Step-by-Step Example
# Trace through the algorithm
matrix = [[9, 9, 4], [6, 6, 8], [2, 1, 1]]
print("Matrix:")
for row in matrix:
print(row)
print("\nLongest paths from each starting cell:")
solution = Solution()
# Manually check a few cells to show the process
test_matrix = [[9, 9, 4], [6, 6, 8], [2, 1, 1]]
sol = Solution()
# The path 1?6?8?9 gives us length 4
print("Starting from (2,1) with value 1:")
print("1 ? 6 ? 8 ? 9 = length 4")
result = sol.longestIncreasingPath(test_matrix)
print(f"\nOverall longest path: {result}")
Matrix: [9, 9, 4] [6, 6, 8] [2, 1, 1] Longest paths from each starting cell: Starting from (2,1) with value 1: 1 ? 6 ? 8 ? 9 = length 4 Overall longest path: 4
Time and Space Complexity
| Aspect | Complexity | Explanation |
|---|---|---|
| Time | O(m × n) | Each cell is computed once due to memoization |
| Space | O(m × n) | DP table and recursion stack space |
Conclusion
The longest increasing path problem is efficiently solved using DFS with memoization. The key insight is that each cell's longest path depends only on its neighbors with greater values, making dynamic programming ideal for avoiding redundant computations.
---