![]() |
VOOZH | about |
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].
Table of Content
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.
4
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:
4
Related article: