using
System;
using
System.Collections.Generic;
public
class
Node
{
public
int
i, j, dist;
public
Node(
int
i,
int
j,
int
dist)
{
this
.i = i;
this
.j = j;
this
.dist = dist;
}
}
public
class
MinDistanceFromaGuardInBank
{
static
int
M = 5;
static
int
N = 5;
static
int
[] row = { -1, 0, 1, 0 };
static
int
[] col = { 0, 1, 0, -1 };
static
bool
isValid(
int
i,
int
j)
{
if
((i < 0 || i > M - 1) || (j < 0 || j > N - 1))
return
false
;
return
true
;
}
static
bool
isSafe(
int
i,
int
j,
char
[,] matrix,
int
[,] output)
{
if
(matrix[i,j] !=
'O'
|| output[i,j] != -1)
{
return
false
;
}
return
true
;
}
static
void
findDistance(
char
[,] matrix)
{
int
[,] output =
new
int
[M,N];
Queue<Node> q =
new
Queue<Node>();
for
(
int
i = 0; i < M; i++)
{
for
(
int
j = 0; j < N; j++)
{
output[i, j] = -1;
if
(matrix[i, j] ==
'G'
)
{
q.Enqueue(
new
Node(i, j, 0));
output[i, j] = 0;
}
}
}
while
(q.Count != 0)
{
Node curr = q.Peek();
int
x = curr.i;
int
y = curr.j;
int
dist = curr.dist;
for
(
int
i = 0; i < 4; i++)
{
if
(isValid(x + row[i], y + col[i]))
{
if
(isSafe(x + row[i], y + col[i],matrix, output))
{
output[x + row[i] , y + col[i]] = dist + 1;
q.Enqueue(
new
Node(x + row[i],y + col[i],dist + 1));
}
}
}
q.Dequeue();
}
for
(
int
i = 0; i < M; i++)
{
for
(
int
j = 0; j < N; j++)
{
Console.Write(output[i,j] +
" "
);
}
Console.WriteLine();
}
}
static
public
void
Main ()
{
char
[,] matrix ={ {
'O'
,
'O'
,
'O'
,
'O'
,
'G'
},
{
'O'
,
'W'
,
'W'
,
'O'
,
'O'
},
{
'O'
,
'O'
,
'O'
,
'W'
,
'O'
},
{
'G'
,
'W'
,
'W'
,
'W'
,
'O'
},
{
'O'
,
'O'
,
'O'
,
'O'
,
'G'
} };
findDistance(matrix);
}
}