diff --git a/LongestPathInMatrix.java b/LongestPathInMatrix.java new file mode 100644 index 0000000..14f068c --- /dev/null +++ b/LongestPathInMatrix.java @@ -0,0 +1,77 @@ +/ Java program to find the longest path in a matrix +// with given constraints + +class LongestPathInMatrix +{ + public static int n = 3; + + // Function that returns length of the longest path + // beginning with mat[i][j] + // This function mainly uses lookup table dp[n][n] + static int findLongestFromACell(int i, int j, int mat[][], int dp[][]) + { + // Base case + if (i<0 || i>=n || j<0 || j>=n) + return 0; + + // If this subproblem is already solved + if (dp[i][j] != -1) + return dp[i][j]; + + // Since all numbers are unique and in range from 1 to n*n, + // there is atmost one possible direction from any cell + if (j0 && (mat[i][j] +1 == mat[i][j-1])) + return dp[i][j] = 1 + findLongestFromACell(i,j-1,mat,dp); + + if (i>0 && (mat[i][j] +1 == mat[i-1][j])) + return dp[i][j] = 1 + findLongestFromACell(i-1,j,mat,dp); + + if (i