VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-longest-path-in-a-matrix-with-given-constraints/

⇱ Find the longest path in a matrix with given constraints - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the longest path in a matrix with given constraints

Last Updated : 23 Jul, 2025

Given an n*m matrix where all numbers are distinct, the task is to find the maximum length path (starting from any cell) such that all cells along the path are in increasing order with a difference of 1
We can move in 4 directions from a given cell (i, j), i.e., we can move to (i+1, j) or (i, j+1) or (i-1, j) or (i, j-1) with the condition that the adjacent cells have a difference of 1.

Example:

Input:
n = 3, m = 3
matrix[][] = [[1 2 9],
[5 3 8],
[4 6 7]]

Output: 4
Explanation: The longest increasing path is [6, 7, 8, 9].

Input:
n = 3, m = 3
matrix[][] = [[3 4 5],
[6 7 8],
[10 2 1]]
Output: 3
Explanation: The longest increasing path is [3, 4, 5].

Using Depth First Search - O((n*m)^(n*m)) Time and O(n*m) Space

The idea is to perform a depth-first search (DFS) from every cell in the matrix, exploring all possible paths that satisfy the strictly increasing condition. For each cell, we will recursively try moving in all four directions (up, down, left, right), keeping track of the current path length and ensuring that the next cell has a strictly higher value than the current cell.


Output
4

Using DFS and Memoization - O(n*m) Time and O(n*m) Space

The idea is to use memoization to avoid recomputing same subproblems. In the recursive solution, multiple recursive calls can explore the same cell multiple times from different paths, leading to exponential time complexity.

For example, if a cell can be reached through multiple different paths, the recursive DFS will recompute the maximum path length for that cell each time it is encountered, resulting in repeated and unnecessary calculations.

Memoization solves this by storing the maximum path length for each cell after its first computation, allowing immediate retrieval of previously calculated results and preventing redundant recursive calls.

Step by step approach:

  1. Create a memoization matrix[][] memo of size n*m, initialized with -1 to indicate no computations have been made yet.
  2. Each memo[i][j] will store the maximum path length starting from cell (i, j).
  3. If a cell's maximum path length is not yet computed (memo[i][j] == -1), perform the DFS exploration.
  4. During DFS, explore all four adjacent cells that satisfy the strictly increasing condition of difference 1.
  5. When a valid path is found from a cell, store its maximum path length in memo[i][j].
  6. If a cell's maximum path length is already computed, directly return the memoized value.

Output
4

Related article:

Comment