using
System;
using
System.Collections.Generic;
public
class
Graph {
private
List<
int
>[] adj;
public
Graph(
int
v)
{
adj =
new
List<
int
>[ v ];
for
(
int
i = 0; i < v; i++)
adj[i] =
new
List<
int
>();
}
public
void
Add_edges(
int
u,
int
v) { adj[u].Add(v); }
public
int
DFS(
int
s,
int
d, HashSet<
int
> visited)
{
if
(s == d)
return
0;
int
res = Int32.MaxValue - 1;
visited.Add(s);
foreach
(
int
item
in
adj[s])
{
if
(!visited.Contains(item)) {
res = Math.Min(res,
1 + DFS(item, d, visited));
}
}
return
res;
}
}
public
class
GFG
{
static
readonly
int
N = 4;
static
bool
Is_safe(
int
[, ] arr,
int
i,
int
j)
{
if
((i < 0 || i >= N) || (j < 0 || j >= N)
|| arr[i, j] == 0)
return
false
;
return
true
;
}
static
int
Min_moves(
int
[, ] arr)
{
int
s = -1, d = -1, V = N * N;
int
k = 0;
Graph g =
new
Graph(V);
for
(
int
i = 0; i < N; i++) {
for
(
int
j = 0; j < N; j++) {
if
(arr[i, j] != 0) {
if
(Is_safe(arr, i, j + 1))
g.Add_edges(k, k + 1);
if
(Is_safe(arr, i, j - 1))
g.Add_edges(k, k - 1);
if
(Is_safe(arr, i + 1, j))
g.Add_edges(k, k + N);
if
(Is_safe(arr, i - 1, j))
g.Add_edges(k, k - N);
}
if
(arr[i, j] == 1)
s = k;
else
if
(arr[i, j] == 2)
d = k;
k++;
}
}
HashSet<
int
> visited =
new
HashSet<
int
>();
return
g.DFS(s, d, visited);
}
static
void
Main(
string
[] args)
{
int
[, ] arr = { { 3, 3, 1, 0 },
{ 3, 0, 3, 3 },
{ 2, 3, 0, 3 },
{ 0, 3, 3, 3 } };
int
ans = Min_moves(arr);
Console.WriteLine(ans);
}
}