# LeetCode – Longest Increasing Path in a Matrix (Java)

Given an integer matrix, find the length of the longest increasing path.

From each cell, you can either move to four directions: left, right, up or down. You may NOT move diagonally or move outside of the boundary

Java Solution 1 - DFS

This solution is over time limit.

 public int longestIncreasingPath(int[][] matrix) { if(matrix==null||matrix.length==0||matrix[0].length==0) return 0;   int[] max = new int[1]; for(int i=0; i=0 && x=0 && ymatrix[i][j]){ dfs(matrix, x, y, max, len+1); } } }

Java Solution - Optimized

 public class Solution { int[] dx = {-1, 1, 0, 0}; int[] dy = {0, 0, -1, 1};   public int longestIncreasingPath(int[][] matrix) { if(matrix==null||matrix.length==0||matrix[0].length==0) return 0;   int[][] mem = new int[matrix.length][matrix[0].length]; int longest=0;   for(int i=0; i=0&&y>=0&&xmatrix[i][j]){ mem[i][j]=Math.max(mem[i][j], dfs(matrix, x, y, mem)); } }   return ++mem[i][j]; } }
Category >> Algorithms
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code>
String foo = "bar";
</code></pre>
• Apurv Dubey

that’s awesome solutions!