using
System;
using
System.Collections.Generic;
class
GFG {
static
bool
BFS(List<List<
int
>> dist,
int
s) {
int
n = dist.Count;
Queue<Tuple<
int
,
int
>> q =
new
Queue<Tuple<
int
,
int
>>();
List<List<
int
>> vis =
new
List<List<
int
>>();
for
(
int
i = 0; i < n; i++) {
vis.Add(
new
List<
int
>());
for
(
int
j = 0; j < n; j++) {
vis[i].Add(0);
}
}
q.Enqueue(
new
Tuple<
int
,
int
>(0, 0));
vis[0][0] = 1;
int
[] delRow = { -1, 0, 1, 0 };
int
[] delCol = { 0, 1, 0, -1 };
while
(q.Count != 0) {
Tuple<
int
,
int
> current = q.Dequeue();
int
r = current.Item1;
int
c = current.Item2;
if
(r == n - 1 && c == n - 1) {
return
true
;
}
for
(
int
i = 0; i < 4; i++) {
int
nrow = r + delRow[i];
int
ncol = c + delCol[i];
if
(nrow >= 0 && nrow < n && ncol >= 0
&& ncol < n && dist[nrow][ncol] >= s
&& vis[nrow][ncol] == 0) {
q.Enqueue(
new
Tuple<
int
,
int
>(nrow, ncol));
vis[nrow][ncol] = 1;
}
}
}
return
false
;
}
static
void
Main(
string
[] args) {
int
n = 3;
int
m = 3;
List<List<
int
>> grid =
new
List<List<
int
>> {
new
List<
int
> { 0, 0, 1 },
new
List<
int
> { 0, -1, 0 },
new
List<
int
> { 0, 0, 0 }
};
List<List<
int
>> vis =
new
List<List<
int
>>();
List<List<
int
>> dist =
new
List<List<
int
>>();
Queue<Tuple<Tuple<
int
,
int
>,
int
>> q =
new
Queue<Tuple<Tuple<
int
,
int
>,
int
>>();
for
(
int
i = 0; i < n; i++) {
vis.Add(
new
List<
int
>());
dist.Add(
new
List<
int
>());
for
(
int
j = 0; j < m; j++) {
vis[i].Add(0);
dist[i].Add(0);
if
(grid[i][j] == 1) {
vis[i][j] = 1;
q.Enqueue(
new
Tuple<Tuple<
int
,
int
>,
int
>(
new
Tuple<
int
,
int
>(i, j), 0));
}
}
}
int
[] delRow = { -1, 0, 1, 0 };
int
[] delCol = { 0, 1, 0, -1 };
while
(q.Count != 0) {
Tuple<Tuple<
int
,
int
>,
int
> current = q.Dequeue();
int
row = current.Item1.Item1;
int
col = current.Item1.Item2;
int
steps = current.Item2;
dist[row][col] = steps;
for
(
int
i = 0; i < 4; i++) {
int
nrow = row + delRow[i];
int
ncol = col + delCol[i];
if
(nrow >= 0 && nrow < n && ncol >= 0
&& ncol < m && vis[nrow][ncol] == 0
&& grid[nrow][ncol] != -1) {
vis[nrow][ncol] = 1;
q.Enqueue(
new
Tuple<Tuple<
int
,
int
>,
int
>(
new
Tuple<
int
,
int
>(nrow, ncol), steps + 1));
}
}
}
int
low = 0, high = 1000000000, ans = 0;
while
(low <= high) {
int
mid = (low + high) / 2;
if
(BFS(dist, mid)) {
ans = mid;
low = mid + 1;
}
else
{
high = mid - 1;
}
}
Console.WriteLine(
"Maximum Safety Factor: "
+ ans);
}
}