using System;
class GFG {
static int R = 3;
static int C = 10;
static Tuple<bool,int> findLongestPathUtil (int[, ] mat, int i, int j, int x, int y, bool[, ] visited) {
if(i == x && j == y)
return new Tuple<bool,int>(true, 0);
if(i < 0 || i >= R || j < 0 || j >= C || mat[i,j] == 0 || visited[i,j])
return new Tuple<bool,int>(false, Int32.MaxValue);
visited[i,j] = true;
int res = Int32.MinValue;
Tuple<bool,int> sol = findLongestPathUtil(mat, i, j-1, x, y, visited);
if(sol.Item1)
res = Math.Max(sol.Item2, res);
sol = findLongestPathUtil(mat, i, j+1, x, y, visited);
if(sol.Item1)
res = Math.Max(sol.Item2, res);
sol = findLongestPathUtil(mat, i-1, j, x, y, visited);
if(sol.Item1)
res = Math.Max(sol.Item2, res);
sol = findLongestPathUtil(mat, i+1, j, x, y, visited);
if(sol.Item1)
res = Math.Max(sol.Item2, res);
visited[i,j] = false;
if(res != Int32.MinValue)
return new Tuple<bool,int>(true, res+1);
else
return new Tuple<bool,int>(false, Int32.MaxValue);
}
static void findLongestPath (int [, ]mat, int i, int j, int x, int y) {
bool[,] visited = new bool[R,C];
Tuple<bool,int> p = findLongestPathUtil(mat, i, j, x, y, visited);
if(p.Item1)
Console.WriteLine("Length of longest possible route is : " + p.Item2);
else
Console.WriteLine("Destination not reachable from given source");
}
public static void Main() {
int[,] mat = new int[,] { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 },
{ 1, 1, 0, 1, 1, 0, 1, 1, 0, 1 },
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };
findLongestPath(mat, 0, 0, 1, 7);
}
}