using
System;
using
System.Collections.Generic;
class
GFG{
class
Pair
{
public
int
first, second;
public
Pair(
int
a,
int
b)
{
first = a;
second = b;
}
}
static
int
row = 5;
static
int
col = 5;
static
int
[,]minDistance =
new
int
[row + 1, col + 1];
static
int
[,]visited =
new
int
[row + 1, col + 1];
static
Queue<Pair> que =
new
Queue<Pair>();
static
bool
isValid(
int
[,]grid,
int
i,
int
j)
{
if
(i < 0 || j < 0 || j >= col ||
i >= row || grid[i, j] != 0 ||
visited[i, j] != 0)
return
false
;
return
true
;
}
static
int
findMinPathminDistance(
int
[,]grid,
int
sourceRow,
int
sourceCol)
{
if
(sourceCol == 0 || sourceCol == col - 1 ||
sourceRow == 0 || sourceRow == row - 1)
return
0;
int
minFromSource = row * col;
int
i = 0;
for
(i = 0; i < row; i++)
for
(
int
j = 0; j < col; j++)
minDistance[i, j] = row * col;
que.Enqueue(
new
Pair(sourceRow, sourceCol));
minDistance[sourceRow, sourceCol] = 0;
visited[sourceRow, sourceCol] = 1;
while
(que.Count > 0)
{
Pair cell = que.Peek();
int
cellRow = cell.first;
int
cellCol = cell.second;
if
(isValid(grid, cellRow + 1, cellCol))
{
que.Enqueue(
new
Pair(cellRow + 1, cellCol));
minDistance[cellRow + 1, cellCol] = Math.Min(
minDistance[cellRow + 1, cellCol],
minDistance[cellRow, cellCol] + 1);
visited[cellRow + 1, cellCol] = 1;
}
if
(isValid(grid, cellRow - 1, cellCol))
{
que.Enqueue(
new
Pair(cellRow - 1, cellCol));
minDistance[cellRow - 1, cellCol] = Math.Min(
minDistance[cellRow - 1, cellCol],
minDistance[cellRow, cellCol] + 1);
visited[cellRow - 1, cellCol] = 1;
}
if
(isValid(grid, cellRow, cellCol + 1))
{
que.Enqueue(
new
Pair(cellRow, cellCol + 1));
minDistance[cellRow, cellCol + 1] = Math.Min(
minDistance[cellRow, cellCol + 1],
minDistance[cellRow, cellCol] + 1);
visited[cellRow, cellCol + 1] = 1;
}
if
(isValid(grid, cellRow, cellCol - 1))
{
que.Enqueue(
new
Pair(cellRow, cellCol - 1));
minDistance[cellRow, cellCol - 1] = Math.Min(
minDistance[cellRow, cellCol - 1],
minDistance[cellRow, cellCol] + 1);
visited[cellRow, cellCol - 1] = 1;
}
que.Dequeue();
}
i = 0;
for
(i = 0; i < col; i++)
minFromSource = Math.Min(minFromSource,
minDistance[0, i]);
for
(i = 0; i < col; i++)
minFromSource = Math.Min(minFromSource,
minDistance[row - 1, i]);
for
(i = 0; i < row; i++)
minFromSource = Math.Min(minFromSource,
minDistance[i, 0]);
for
(i = 0; i < row; i++)
minFromSource = Math.Min(minFromSource,
minDistance[i, col - 1]);
if
(minFromSource == row * col)
return
-1;
return
minFromSource;
}
public
static
void
Main(String []args)
{
int
sourceRow = 3, sourceCol = 3;
int
[,]grid = { { 1, 1, 1, 1, 0 },
{ 0, 0, 1, 0, 1 },
{ 0, 0, 1, 0, 1 },
{ 1, 0, 0, 0, 1 },
{ 1, 1, 0, 1, 0 } };
Console.WriteLine(findMinPathminDistance(
grid, sourceRow, sourceCol));
}
}