




Sponsored
Sponsored
This approach uses a combination of Depth First Search (DFS) and memoization to solve the problem efficiently. We explore each cell, attempting to find the longest increasing path starting from that cell. To avoid recalculating the path length for each call from the same cell, we use memoization to store already computed results.
The time complexity is O(m * n) because each cell is computed once and cached. The space complexity is also O(m * n) due to the memoization table.
1def longestIncreasingPath(matrix):
2    if not matrix or not matrix[0]:
3        return 0
4    
5    m, n = len(matrix), len(matrix[0])
6    memo = [[-1] * n for _ in range(m)]
7    
8    def dfs(x, y):
9        if memo[x][y] != -1:
10            return memo[x][y]
11        
12        directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]
13        max_len = 1
14        
15        for dx, dy in directions:
16            nx, ny = x + dx, y + dy
17            if 0 <= nx < m and 0 <= ny < n and matrix[nx][ny] > matrix[x][y]:
18                max_len = max(max_len, 1 + dfs(nx, ny))
19        
20        memo[x][y] = max_len
21        return max_len
22    
23    return max(dfs(x, y) for x in range(m) for y in range(n))In this Python solution, we define a helper function dfs that performs DFS on the matrix starting from a given cell. We utilize a memo table to store the longest path from each cell to avoid redundant calculations, improving performance significantly. The main function starts by iterating over each cell to compute the maximum length path by considering each cell as a starting point.
This approach systematically calculates the longest increasing path dynamically by first iterating over the matrix and then updating results based on previously computed values. By using a dynamic programming table, we determine, for each cell, the longest chain it can contribute to incrementally.
The time complexity is O(m * n) due to the fact that each matrix cell can be a starting point and is only calculated once with memoization guidance. The space complexity is O(m * n) because a result is stored for each cell in the DP table.
1var longestIncreasingPath = function(matrix) 
The JavaScript solution uses dynamic programming. For each cell, the function dfs recursively explores valid neighbors, resulting in the longest increasing path starting from that cell. The result for each cell is stored in a DP table before being returned, which ensures efficiency by preventing the recalculation of already known results.