using
System;
using
System.Collections.Generic;
public
class
Solution
{
public
static
bool
IsValidCell(
int
r,
int
c,
int
numRows,
int
numCols)
{
return
r >= 0 && c >= 0 && r < numRows && c < numCols;
}
public
static
bool
IsAdjacentMove(
int
i,
int
j)
{
return
(i == 1 && j == 0) || (i == -1 && j == 0)
|| (i == 0 && j == 1) || (i == 0 && j == -1);
}
public
static
void
CalculateDistances(
char
[][] grid,
long
[][] dist,
int
startRow,
int
startCol,
int
numRows,
int
numCols)
{
Queue<Tuple<
int
,
int
>> dq =
new
Queue<Tuple<
int
,
int
>>();
dq.Enqueue(
new
Tuple<
int
,
int
>(startRow, startCol));
dist[startRow][startCol] = 0;
while
(dq.Count > 0)
{
Tuple<
int
,
int
> current = dq.Dequeue();
int
r = current.Item1, c = current.Item2;
for
(
int
i = -2; i <= 2; i++)
{
for
(
int
j = -2; j <= 2; j++)
{
int
nr = r + i, nc = c + j;
if
(IsValidCell(nr, nc, numRows, numCols))
{
if
(grid[nr][nc] ==
'.'
)
{
if
(IsAdjacentMove(i, j) && dist[nr][nc] > dist[r])
{
dist[nr][nc] = dist[r];
dq.Enqueue(
new
Tuple<
int
,
int
>(nr, nc));
}
else
if
(!IsAdjacentMove(i, j) && dist[nr][nc] > dist[r] + 1)
{
dist[nr][nc] = dist[r] + 1;
dq.Enqueue(
new
Tuple<
int
,
int
>(nr, nc));
}
}
}
}
}
}
}
public
static
void
Main(
string
[] args)
{
char
[][] grid =
{
new
char
[] {
'.'
,
'.'
,
'#'
,
'.'
},
new
char
[] {
'.'
,
'.'
,
'#'
,
'.'
},
new
char
[] {
'.'
,
'#'
,
'.'
,
'.'
},
new
char
[] {
'.'
,
'#'
,
'.'
,
'.'
}
};
int
numRows = 4, numCols = 4, startRow = 1,
startCol = 1, endRow = 4, endCol = 4;
startRow -= 1;
startCol -= 1;
endRow -= 1;
endCol -= 1;
long
[][] distances =
new
long
[numRows][];
for
(
int
i = 0; i < numRows; i++)
{
distances[i] =
new
long
[numCols];
for
(
int
j = 0; j < numCols; j++)
{
distances[i][j] = (
long
)1e9;
}
}
CalculateDistances(grid, distances, startRow, startCol, numRows, numCols);
if
(distances[endRow][endCol] == 1e9)
Console.WriteLine(-1);
else
Console.WriteLine(distances[endRow][endCol]);
}
}