using
System;
using
System.Collections.Generic;
public
class
GFG {
public
static
readonly
int
R = 4;
public
static
readonly
int
C = 5;
public
static
bool
Check(
int
i,
int
j,
int
n,
int
m,
int
[, ] mat)
{
if
(i >= 0 && i < n && j >= 0 && j < m) {
if
(mat[i, j] == 0) {
return
true
;
}
}
return
false
;
}
public
static
int
findMinSteps(
int
[, ] mat,
int
n,
int
m)
{
int
indx, indy;
indx = indy = -1;
for
(
int
i = 0; i < n; i++) {
for
(
int
j = 0; j < m; j++) {
if
(mat[i, j] == 2) {
indx = i;
indy = j;
break
;
}
}
if
(indx != -1) {
break
;
}
}
Queue<
int
[]> q =
new
Queue<
int
[]>();
q.Enqueue(
new
int
[] { indx, indy, 0 });
if
(Check(indx, indy, n, m, mat)) {
return
0;
}
bool
[, ] vis =
new
bool
[n, m];
while
(q.Count != 0) {
int
[] curr = q.Dequeue();
int
x = curr[0];
int
y = curr[1];
int
val = curr[2];
if
(x == 0 || x == (n - 1) || y == 0
|| y == (m - 1)) {
return
val;
}
vis[x, y] =
true
;
if
(Check(x - 1, y, n, m, mat)) {
if
(!vis[x - 1, y]) {
q.Enqueue(
new
int
[] { x - 1, y, val + 1 });
}
}
if
(Check(x + 1, y, n, m, mat)) {
if
(!vis[x + 1, y]) {
q.Enqueue(
new
int
[] { x + 1, y, val + 1 });
}
}
if
(Check(x, y + 1, n, m, mat)) {
if
(!vis[x, y + 1]) {
q.Enqueue(
new
int
[] { x, y + 1, val + 1 });
}
}
if
(Check(x, y - 1, n, m, mat)) {
if
(!vis[x, y - 1]) {
q.Enqueue(
new
int
[] { x, y - 1, val + 1 });
}
}
}
return
-1;
}
static
public
void
Main(
string
[] args)
{
int
[, ] mat = { { 1, 1, 1, 0, 1 },
{ 1, 0, 2, 0, 1 },
{ 0, 0, 1, 0, 1 },
{ 1, 0, 1, 1, 0 } };
Console.WriteLine(findMinSteps(mat, 4, 5));
}
}