using
System;
using
System.Collections.Generic;
public
class
Program
{
public
static
int
ShortestPath(
int
[, ] mat,
int
k)
{
int
n = mat.GetLength(0);
int
m = mat.GetLength(1);
if
(n == 1 && m == 1 && (mat[0, 0] == 0 || k >= 1))
return
0;
bool
[, , ] visited =
new
bool
[n, m, k + 1];
int
steps = 0;
Queue<
int
[]> q =
new
Queue<
int
[]>();
q.Enqueue(
new
int
[] { 0, 0, k });
int
[] ar1 = { 1, -1, 0, 0 };
int
[] ar2 = { 0, 0, -1, 1 };
while
(q.Count != 0) {
int
size = q.Count;
steps++;
while
(size-- > 0) {
int
[] curr = q.Dequeue();
int
i = curr[0], j = curr[1], w = curr[2];
visited[i, j, w] =
true
;
for
(
int
dir = 0; dir < 4; dir++) {
int
new_x = i + ar1[dir];
int
new_y = j + ar2[dir];
int
new_k = w;
if
(new_x >= 0 && new_x < n
&& new_y >= 0 && new_y < m) {
if
(mat[new_x, new_y] == 0
&& !visited[new_x, new_y,
new_k]) {
if
(new_x == n - 1
&& new_y == m - 1)
return
steps;
q.Enqueue(
new
int
[] {
new_x, new_y, new_k });
visited[new_x, new_y, new_k]
=
true
;
}
else
if
(mat[new_x, new_y] == 1
&& new_k >= 1
&& !visited[new_x, new_y,
new_k - 1]) {
if
(new_x == n - 1
&& new_y == m - 1)
return
steps;
q.Enqueue(
new
int
[] {
new_x, new_y, new_k - 1 });
visited[new_x, new_y, new_k - 1]
=
true
;
}
}
}
}
}
return
-1;
}
public
static
void
Main()
{
int
[, ] mat
= { { 0, 0, 0 }, { 0, 0, 1 }, { 0, 1, 0 } };
int
K = 1;
Console.WriteLine(ShortestPath(mat, K));
}
}