Tutorialspoint
Problem
Solution
Submissions

Longest Increasing Path

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the length of the longest increasing path in a matrix. You can move in four directions (up, down, left, right) from each cell. You cannot move diagonally or outside the matrix boundaries. An increasing path means each cell value must be strictly greater than the previous cell value.

Example 1
  • Input: matrix = [[9,9,4],[6,6,8],[2,1,1]]
  • Output: 4
  • Explanation:
     Step 1: The longest increasing path is [1, 2, 6, 9]
     Step 2: Path: (2,1) -> (2,0) -> (1,0) -> (0,0)
     Step 3: Values: 1 -> 2 -> 6 -> 9 (strictly increasing)
     Step 4: Length = 4
Example 2
  • Input: matrix = [[3,4,5],[3,2,6],[2,2,1]]
  • Output: 4
  • Explanation:
     Step 1: The longest increasing path is [3, 4, 5, 6]
     Step 2: Path: (0,0) -> (0,1) -> (0,2) -> (1,2)
     Step 3: Values: 3 -> 4 -> 5 -> 6 (strictly increasing)
     Step 4: Length = 4
Constraints
  • 1 ≤ matrix.length, matrix[i].length ≤ 200
  • 0 ≤ matrix[i][j] ≤ 2^31 - 1
  • You must find the longest strictly increasing path
  • Time Complexity: O(m * n)
  • Space Complexity: O(m * n)
MatrixCapgeminiPhillips
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use dynamic programming with memoization to avoid recalculating paths
  • For each cell, try all four directions and find the maximum path length
  • Use DFS (Depth-First Search) with memoization to explore all possible paths
  • A cell's longest path is 1 + maximum of its valid neighbors' longest paths
  • Create a memoization table to store computed results for each cell
  • Only move to a cell if its value is strictly greater than current cell

Steps to solve by this approach:

 Step 1: Create a memoization table to store computed results for each cell
 Step 2: For each cell in the matrix, perform DFS to find the longest increasing path
 Step 3: In DFS, check all four directions (up, down, left, right) from current cell
 Step 4: Only move to a neighbor if its value is strictly greater than current cell
 Step 5: Recursively calculate the longest path from valid neighbors
 Step 6: Store the result in memoization table to avoid recalculation
 Step 7: Return the maximum path length found among all cells

Submitted Code :