// C# program to find the longest path // in a matrix with given constraints using System; class GfG { static int longestPath(int i, int j, int[,] matrix, int[,] memo) { // If value is memoized if (memo[i, j] != -1) { return memo[i, j]; } int ans = 1; int[,] dir = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } }; // Check for all 4 directions for (int k = 0; k < dir.GetLength(0); k++) { int x = i + dir[k, 0]; int y = j + dir[k, 1]; // If new cells are valid and // increasing by 1. if (x >= 0 && x < matrix.GetLength(0) && y >= 0 && y < matrix.GetLength(1) && matrix[x, y] == matrix[i, j] + 1) { ans = Math.Max(ans, 1 + longestPath(x, y, matrix, memo)); } } return memo[i, j] = ans; } static int longestIncreasingPath(int[,] matrix) { int n = matrix.GetLength(0), m = matrix.GetLength(1); int[,] memo = new int[n, m]; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { memo[i, j] = -1; } } int ans = 0; // Find length of longest path // from each cell i, j for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { ans = Math.Max(ans, longestPath(i, j, matrix, memo)); } } return ans; } static void Main(string[] args) { int[,] matrix = { { 1, 2, 9 }, { 5, 3, 8 }, { 4, 6, 7 } }; Console.WriteLine(longestIncreasingPath(matrix)); } }