// C# program to find
// longest increasing path in matrix
using System;
class GfG {
// Function which checks if the cell is valid
// and its value is greater than previous cell.
static bool validCell(int i, int j, int[, ] matrix,
int prev) {
return (i >= 0 && i < matrix.GetLength(0) && j >= 0
&& j < matrix.GetLength(1)
&& matrix[i, j] > prev);
}
static int pathRecur(int i, int j, int[, ] matrix,
int[, ] memo) {
// If answer exists in memo table.
if (memo[i, j] != -1)
return memo[i, j];
// include current cell in answer
int ans = 1;
// direction vectors to move in 4 directions
int[, ] dir
= { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } };
for (int d = 0; d < 4; d++) {
int x = i + dir[d, 0], y = j + dir[d, 1];
// Check if the cell is valid
if (validCell(x, y, matrix, matrix[i, j])) {
ans = Math.Max(
ans, 1 + pathRecur(x, y, matrix, memo));
}
}
// Memoize the answer
// and return it.
memo[i, j] = ans;
return ans;
}
static int longIncPath(int[, ] matrix, int n, int m) {
int ans = 0;
// Initialize dp table
int[, ] memo = new int[n, m];
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
memo[i, j] = -1;
}
}
// Check longest increasing path
// for each cell.
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
ans = Math.Max(
ans, pathRecur(i, j, matrix, memo));
}
}
return ans;
}
static void Main(string[] args) {
int n = 3, m = 3;
int[, ] matrix
= { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
Console.WriteLine(longIncPath(matrix, n, m));
}
}