using
System;
using
System.Collections.Generic;
public
class
GFG {
static
int
row;
static
int
col;
public
class
Pair {
public
int
x;
public
int
y;
public
int
identity;
public
Pair(
int
x,
int
y,
int
identity)
{
this
.x = x;
this
.y = y;
this
.identity = identity;
}
}
public
static
void
ClosestDistance(
int
[][] grid)
{
row = grid.Length;
col = grid[0].Length;
int
id = 1;
Queue<Pair> q =
new
Queue<Pair>();
int
[][] visited =
new
int
[row][];
for
(
int
i = 0; i < row; i++) {
visited[i] =
new
int
[col];
}
int
[][] distance =
new
int
[row][];
for
(
int
i = 0; i < row; i++) {
distance[i] =
new
int
[col];
}
for
(
int
i = 0; i < row; i++) {
for
(
int
j = 0; j < col; j++) {
if
(grid[i][j] == 1 && visited[i][j] == 0) {
Dfs(grid, visited, q, i, j, id);
id++;
}
}
}
int
ans = bfs(grid, visited, distance, q);
Console.WriteLine(ans);
}
static
int
[] dirx = { 0, 1, 0, -1 };
static
int
[] diry = { 1, 0, -1, 0 };
public
static
void
Dfs(
int
[][] grid,
int
[][] visited,
Queue<Pair> q,
int
i,
int
j,
int
id)
{
visited[i][j] = id;
q.Enqueue(
new
Pair(i, j, id));
for
(
int
idx = 0; idx < 4; idx++) {
int
x = i + dirx[idx];
int
y = j + diry[idx];
if
(IsValid(x, y) && grid[x][y] == 1
&& visited[x][y] == 0) {
Dfs(grid, visited, q, x, y, id);
}
}
}
static
int
bfs(
int
[][] grid,
int
[][] visited,
int
[][] distance, Queue<Pair> q)
{
while
(q.Count != 0) {
Pair p = q.Dequeue();
for
(
int
i = 0; i < 4; i++) {
int
x = p.x + dirx[i];
int
y = p.y + diry[i];
if
(IsValid(x, y) && visited[x][y] == 0) {
q.Enqueue(
new
Pair(x, y, p.identity));
distance[x][y] = distance[p.x][p.y] + 1;
visited[x][y] = p.identity;
}
else
if
(IsValid(x, y) && visited[x][y] != 0
&& visited[x][y]
!= visited[p.x][p.y]) {
return
distance[x][y]
+ distance[p.x][p.y];
}
}
}
return
-1;
}
static
bool
IsValid(
int
x,
int
y)
{
if
(x < 0 || x >= row || y < 0 || y >= col)
return
false
;
return
true
;
}
static
public
void
Main(
string
[] args)
{
int
[][] grid = {
new
int
[] { 1, 0, 0, 0, 1 },
new
int
[] { 1, 1, 0, 0, 0 },
new
int
[] { 0, 0, 0, 0, 0 },
new
int
[] { 0, 0, 1, 1, 1 } };
ClosestDistance(grid);
}
}