using
System;
using
System.Collections.Generic;
using
System.Linq;
class
Program
{
static
bool
IsValid(
int
r,
int
c,
int
N)
{
return
r >= 0 && c >= 0 && r < N && c < N;
}
static
int
Solve(List<List<
int
>> maze,
int
initialDirection, List<Tuple<
int
,
int
>> directions,
int
N)
{
Queue<List<
int
>> dq =
new
Queue<List<
int
>>();
dq.Enqueue(
new
List<
int
> { 0, 0, initialDirection });
int
[,] dist =
new
int
[N, N];
for
(
int
i = 0; i < N; i++)
{
for
(
int
j = 0; j < N; j++)
{
dist[i, j] =
int
.MaxValue;
}
}
dist[0, 0] = 0;
while
(dq.Count > 0)
{
List<
int
> ele = dq.Dequeue();
int
r = ele[0];
int
c = ele[1];
int
currentDirection = ele[2];
for
(
int
i = 0; i < 4; i++)
{
int
nr = r + directions[i].Item1;
int
nc = c + directions[i].Item2;
if
(IsValid(nr, nc, N) && maze[nr][nc] == 1)
{
int
cost = (i == currentDirection) ? 0 : 1;
if
(dist[nr, nc] > dist[r, c] + cost)
{
dist[nr, nc] = dist[r, c] + cost;
if
(cost == 0)
{
dq.Enqueue(
new
List<
int
> { nr, nc, i });
}
else
{
dq.Enqueue(
new
List<
int
> { nr, nc, i });
}
}
}
}
}
return
dist[N - 1, N - 1];
}
static
int
MinimumTurns(
int
N, List<List<
int
>> maze)
{
List<Tuple<
int
,
int
>> directions =
new
List<Tuple<
int
,
int
>>
{
Tuple.Create(0, 1), Tuple.Create(1, 0), Tuple.Create(0, -1), Tuple.Create(-1, 0)
};
int
res =
new
int
[]
{
Solve(maze, 0, directions, N),
Solve(maze, 1, directions, N),
Solve(maze, 2, directions, N),
Solve(maze, 3, directions, N)
}.Min();
return
res ==
int
.MaxValue ? -1 : res;
}
static
void
Main()
{
int
N = 3;
List<List<
int
>> maze =
new
List<List<
int
>>
{
new
List<
int
> { 1, 0, 1 },
new
List<
int
> { 1, 1, 0 },
new
List<
int
> { 0, 1, 1 }
};
Console.WriteLine(MinimumTurns(N, maze));
}
}