Table of Contents

# Longest Increasing Path in a Matrix – LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

Given an `m x n`

integers `matrix`

, return *the length of the longest increasing path in *`matrix`

.

From each cell, you can either move in four directions: left, right, up, or down. You **may not** move **diagonally** or move **outside the boundary** (i.e., wrap-around is not allowed).

**Example 1:**

Input:matrix = [[9,9,4],[6,6,8],[2,1,1]]Output:4Explanation:The longest increasing path is`[1, 2, 6, 9]`

.

**Example 2:**

Input:matrix = [[3,4,5],[3,2,6],[2,2,1]]Output:4Explanation:The longest increasing path is`[3, 4, 5, 6]`

. Moving diagonally is not allowed.

**Example 3:**

Input:matrix = [[1]]Output:1

**Constraints:**

`m == matrix.length`

`n == matrix[i].length`

`1 <= m, n <= 200`

`0 <= matrix[i][j] <= 2`

^{31}- 1

# C++ Longest Increasing Path in a Matrix LeetCode Solution

```
``````
int moves[4][2] = { {-1,0},{1,0},{0,-1},{0,1} }; // all the moves available to us - top, down, left, right
int longestIncreasingPath(vector<vector<int>>& matrix) {
int maxPath = 1; // atleast one cell can always be selected in the path
// explore each cell of matrix to find longest path achievable from that cell and finally return the maximum
for(int i = 0; i < size(matrix); i++)
for(int j = 0; j < size(matrix[0]); j++)
maxPath = max(maxPath, solve(matrix, i, j));
return maxPath;
}
// recursive solver for each cell
int solve(vector<vector<int>>& mat, int i, int j){
int MAX = 1; // max length of path starting from cell i,j of matrix
// choosing all the 4 moves available for current cell
for(int k = 0; k < 4; k++){
int new_i = i + moves[k][0], new_j = j + moves[k][1];
// bound checking as well as move to next cell only when it is greater in value
if(new_i < 0 || new_j < 0 || new_i >= size(mat) || new_j >= size(mat[0]) || mat[new_i][new_j] <= mat[i][j]) continue;
// MAX will be updated each time to store maximum of path length from each move
MAX = max(MAX, 1 + solve(mat, new_i, new_j));
}
return MAX;
}
```

# Java Longest Increasing Path in a Matrix LeetCode Solution

```
``````
public class Solution {
public int longestIncreasingPath(int[][] matrix) {
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
return 0;
}
int[][] cache = new int[matrix.length][matrix[0].length];
int max = 0;
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[0].length; j++) {
int length = findSmallAround(i, j, matrix, cache, Integer.MAX_VALUE);
max = Math.max(length, max);
}
}
return max;
}
private int findSmallAround(int i, int j, int[][] matrix, int[][] cache, int pre) {
// if out of bond OR current cell value larger than previous cell value.
if (i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length || matrix[i][j] >= pre) {
return 0;
}
// if calculated before, no need to do it again
if (cache[i][j] > 0) {
return cache[i][j];
} else {
int cur = matrix[i][j];
int tempMax = 0;
tempMax = Math.max(findSmallAround(i - 1, j, matrix, cache, cur), tempMax);
tempMax = Math.max(findSmallAround(i + 1, j, matrix, cache, cur), tempMax);
tempMax = Math.max(findSmallAround(i, j - 1, matrix, cache, cur), tempMax);
tempMax = Math.max(findSmallAround(i, j + 1, matrix, cache, cur), tempMax);
cache[i][j] = ++tempMax;
return tempMax;
}
}
}
```

# Python 3 Longest Increasing Path in a Matrix LeetCode Solution

```
```We can find longest decreasing path instead, the result will be the same. Use `dp`

to record previous results and choose the max `dp`

value of smaller neighbors.

```
def longestIncreasingPath(self, matrix):
def dfs(i, j):
if not dp[i][j]:
val = matrix[i][j]
dp[i][j] = 1 + max(
dfs(i - 1, j) if i and val > matrix[i - 1][j] else 0,
dfs(i + 1, j) if i < M - 1 and val > matrix[i + 1][j] else 0,
dfs(i, j - 1) if j and val > matrix[i][j - 1] else 0,
dfs(i, j + 1) if j < N - 1 and val > matrix[i][j + 1] else 0)
return dp[i][j]
if not matrix or not matrix[0]: return 0
M, N = len(matrix), len(matrix[0])
dp = [[0] * N for i in range(M)]
return max(dfs(x, y) for x in range(M) for y in range(N))
```

Array-1180

String-562

Hash Table-412

Dynamic Programming-390

Math-368

Sorting-264

Greedy-257

Depth-First Search-256

Database-215

Breadth-First Search-200

Tree-195

Binary Search-191

Matrix-176

Binary Tree-160

Two Pointers-151

Bit Manipulation-140

Stack-133

Heap (Priority Queue)-117

Design-116

Graph-108

Simulation-103

Prefix Sum-96

Backtracking-92

Counting-86

Sliding Window-73

Linked List-69

Union Find-66

Ordered Set-48

Monotonic Stack-47

Recursion-43

Trie-41

Binary Search Tree-40

Divide and Conquer-40

Enumeration-39

Bitmask-37

Queue-33

Memoization-32

Topological Sort-31

Geometry-30

Segment Tree-27

Game Theory-24

Hash Function-24

Binary Indexed Tree-21

Interactive-18

Data Stream-17

String Matching-17

Rolling Hash-17

Shortest Path-16

Number Theory-16

Combinatorics-15

Randomized-12

Monotonic Queue-9

Iterator-9

Merge Sort-9

Concurrency-9

Doubly-Linked List-8

Brainteaser-8

Probability and Statistics-7

Quickselect-7

Bucket Sort-6

Suffix Array-6

Minimum Spanning Tree-5

Counting Sort-5

Shell-4

Line Sweep-4

Reservoir Sampling-4

Eulerian Circuit-3

Radix Sort-3

Strongly Connected Componen-t2

Rejection Sampling-2

Biconnected Component-1

## Leave a comment below