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

From each cell, you can move in four directions: left, right, up, or down. You cannot move diagonally or outside the boundary.

Input & Output

Example 1 — Basic 3x3 Matrix
$ Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
Output: 4
💡 Note: The longest increasing path is 1→6→8→9 with length 4. We can start from (2,1) with value 1, move to (1,0) with value 6, then to (1,2) with value 8, then to (0,0) or (0,1) with value 9.
Example 2 — Simple 2x2 Matrix
$ Input: matrix = [[3,4],[5,2]]
Output: 3
💡 Note: The longest increasing path is 2→3→4 with length 3. Start from (1,1) with value 2, move to (0,0) with value 3, then to (0,1) with value 4.
Example 3 — Single Cell
$ Input: matrix = [[1]]
Output: 1
💡 Note: Only one cell exists, so the longest path has length 1.

Constraints

  • m == matrix.length
  • n == matrix[i].length
  • 1 ≤ m, n ≤ 200
  • 0 ≤ matrix[i][j] ≤ 231 - 1

Visualization

Tap to expand
Longest Increasing Path in a Matrix INPUT 3x3 Matrix 9 9 4 6 6 8 2 1 1 Valid moves: 4 directions U L R D [[9,9,4],[6,6,8],[2,1,1]] ALGORITHM STEPS (DFS) 1 Initialize Create memo table for each cell's longest path 2 DFS from each cell Explore all 4 directions if neighbor is greater 3 Memoize results Store path length to avoid recomputation 4 Track maximum Return longest path found across all cells Example DFS from cell (2,1): 1 2 6 6 8 FINAL RESULT Longest Increasing Path 9 9 4 6 6 8 2 1 1 Path: 1 --> 2 --> 6 --> 8 (strictly increasing) OUTPUT 4 [OK] Length verified Key Insight: DFS with memoization avoids redundant exploration. Each cell's longest path is computed once and cached. Time Complexity: O(m*n) - each cell visited once. Space Complexity: O(m*n) for memoization table. TutorialsPoint - Longest Increasing Path in a Matrix | DFS with Memoization
Asked in
Google 45 Facebook 38 Amazon 32 Microsoft 28
78.4K Views
Medium Frequency
~25 min Avg. Time
2.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen