using
System;
using
System.Collections.Generic;
public
class
GFG {
static
bool
isValid(
int
i,
int
j,
int
n,
int
m)
{
if
(i < n && i >= 0 && j < m && j >= 0) {
return
true
;
}
return
false
;
}
class
pair {
public
int
first, second;
public
pair(
int
first,
int
second)
{
this
.first = first;
this
.second = second;
}
}
static
int
zombieInfection(
int
[, ] grid)
{
Queue<pair> q =
new
Queue<pair>();
int
n = grid.GetLength(0);
int
m = grid.GetLength(1);
int
cur = 0, next = 0;
for
(
int
i = 0; i < n; i++) {
for
(
int
j = 0; j < m; j++) {
if
(grid[i, j] == 1) {
q.Enqueue(
new
pair(i, j));
cur++;
}
}
}
int
t = 0;
while
(q.Count != 0) {
for
(
int
i = 0; i < cur; i++) {
pair use = q.Peek();
q.Dequeue();
int
x = use.first, y = use.second;
if
(isValid(x + 1, y, n, m)
&& grid[x + 1, y] == 0) {
grid[x + 1, y] = 1;
q.Enqueue(
new
pair(x + 1, y));
next++;
}
if
(isValid(x - 1, y, n, m)
&& grid[x - 1, y] == 0) {
grid[x - 1, y] = 1;
q.Enqueue(
new
pair(x - 1, y));
next++;
}
if
(isValid(x, y + 1, n, m)
&& grid[x, y + 1] == 0) {
grid[x, y + 1] = 1;
q.Enqueue(
new
pair(x, y + 1));
next++;
}
if
(isValid(x, y - 1, n, m)
&& grid[x, y - 1] == 0) {
grid[x, y - 1] = 1;
q.Enqueue(
new
pair(x, y - 1));
next++;
}
}
if
(next == 0) {
break
;
}
cur = next;
next = 0;
t++;
}
for
(
int
i = 0; i < n; i++) {
for
(
int
j = 0; j < m; j++) {
if
(grid[i, j] == 0) {
return
-1;
}
}
}
return
t;
}
static
public
void
Main()
{
int
[, ] grid =
new
int
[3, 4] { { 0, 1, 0, 1 },
{ 0, 0, 0, 0 },
{ 0, 0, 0, 1 } };
Console.Write(zombieInfection(grid));
}
}