using
System;
using
System.Collections.Generic;
class
Solution
{
private
int
BFS(
int
[][] matrix,
ref
int
x,
ref
int
y)
{
if
(matrix[x][y] == 0)
return
-1;
Queue<
int
[]> q =
new
Queue<
int
[]>();
int
n = matrix.Length;
int
m = matrix[0].Length;
q.Enqueue(
new
int
[] { x, y, 0 });
int
ans = -1;
int
[][] visited =
new
int
[n][];
for
(
int
i = 0; i < n; i++)
{
visited[i] =
new
int
[m];
for
(
int
j = 0; j < m; j++)
{
visited[i][j] = 0;
}
}
while
(q.Count > 0)
{
int
[] v = q.Dequeue();
int
i = v[0], j = v[1], moves = v[2];
if
(i >= n || i < 0 || j >= m || j < 0)
{
ans = moves;
break
;
}
else
{
if
(visited[i][j] == 1)
continue
;
visited[i][j] = 1;
if
(i + 1 >= n || matrix[i + 1][j] == 1)
q.Enqueue(
new
int
[] { i + 1, j, moves + 1 });
if
(i - 1 < 0 || matrix[i - 1][j] == 1)
q.Enqueue(
new
int
[] { i - 1, j, moves + 1 });
if
(j + 1 >= m || matrix[i][j + 1] == 1)
q.Enqueue(
new
int
[] { i, j + 1, moves + 1 });
if
(j - 1 < 0 || matrix[i][j - 1] == 1)
q.Enqueue(
new
int
[] { i, j - 1, moves + 1 });
}
}
return
ans;
}
public
int
MinMoves(
int
[][] matrix,
int
x,
int
y)
{
int
ans = BFS(matrix,
ref
x,
ref
y);
return
(ans >= 1e7) ? -1 : ans - 1;
}
}
class
Program
{
static
void
Main()
{
int
[][] matrix = {
new
int
[] { 0, 1, 0, 0, 0 },
new
int
[] { 0, 1, 1, 0, 0 },
new
int
[] { 0, 1, 1, 1, 0 },
new
int
[] { 0, 0, 0, 1, 1 },
new
int
[] { 0, 0, 0, 1, 0 }
};
int
x = 1, y = 2;
Solution obj =
new
Solution();
Console.WriteLine(obj.MinMoves(matrix, x, y));
}
}