using
System;
using
System.Collections.Generic;
class
GFG {
static
bool
[, ] visited;
static
bool
isSafe(
int
[, ] mat,
bool
[, ] visited,
int
x,
int
y)
{
return
(x >= 0 && x < mat.GetLength(0) && y >= 0
&& y < mat.GetLength(1) && mat[x, y] == 1
&& !visited[x, y]);
}
static
int
findShortestPath(
int
[, ] mat,
int
i,
int
j,
int
x,
int
y,
int
min_dist,
int
dist)
{
if
(i == x && j == y) {
min_dist = Math.Min(dist, min_dist);
return
min_dist;
}
visited[i, j] =
true
;
if
(isSafe(mat, visited, i + 1, j)) {
min_dist = findShortestPath(mat, i + 1, j, x, y,
min_dist, dist + 1);
}
if
(isSafe(mat, visited, i, j + 1)) {
min_dist = findShortestPath(mat, i, j + 1, x, y,
min_dist, dist + 1);
}
if
(isSafe(mat, visited, i - 1, j)) {
min_dist = findShortestPath(mat, i - 1, j, x, y,
min_dist, dist + 1);
}
if
(isSafe(mat, visited, i, j - 1)) {
min_dist = findShortestPath(mat, i, j - 1, x, y,
min_dist, dist + 1);
}
visited[i, j] =
false
;
return
min_dist;
}
static
int
findShortestPathLength(
int
[, ] mat,
int
[] src,
int
[] dest)
{
if
(mat.GetLength(0) == 0
|| mat[src[0], src[1]] == 0
|| mat[dest[0], dest[1]] == 0)
return
-1;
int
row = mat.GetLength(0);
int
col = mat.GetLength(1);
visited =
new
bool
[row, col];
for
(
int
i = 0; i < row; i++) {
for
(
int
j = 0; j < col; j++)
visited[i, j] =
false
;
}
int
dist = Int32.MaxValue;
dist = findShortestPath(mat, src[0], src[1],
dest[0], dest[1], dist, 0);
if
(dist != Int32.MaxValue)
return
dist;
return
-1;
}
public
static
void
Main(
string
[] args)
{
int
[, ] mat =
new
int
[, ] {
{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 0, 1, 0, 1, 1, 1, 0, 1, 1 },
{ 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 },
{ 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 },
{ 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 },
{ 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 },
{ 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 },
{ 1, 1, 0, 0, 0, 0, 1, 0, 0, 1 }
};
int
[] src = { 0, 0 };
int
[] dest = { 3, 4 };
int
dist = findShortestPathLength(mat, src, dest);
if
(dist != -1)
Console.Write(
"Shortest Path is "
+ dist);
else
Console.Write(
"Shortest Path doesn't exist"
);
}
}