-
Notifications
You must be signed in to change notification settings - Fork 0
/
1981.cpp
86 lines (72 loc) · 1.63 KB
/
1981.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
#include <algorithm>
#include <queue>
#include <cstring>
#define N 105
using namespace std;
int n, arr[N][N], in, ax;
queue<pair<int, int>> q;
int xx[4] = {0, 0, -1, 1};
int yy[4] = {1, -1, 0, 0};
bool check[N][N];
bool cross(int minv, int maxv)
{
if(arr[1][1]<minv || arr[1][1]>maxv) return false;
int i;
while (!q.empty())
q.pop();
memset(check, false, sizeof(check));
q.push(make_pair(1, 1));
check[1][1] = true;
while (!q.empty())
{
if (q.front() == make_pair(n, n))
return true;
for (i = 0; i < 4; i++)
{
int nx = q.front().first + xx[i];
int ny = q.front().second + yy[i];
if (nx < 1 || ny < 1 || nx > n || ny > n)
continue;
if (!check[nx][ny] && arr[nx][ny] >= minv && arr[nx][ny] <= maxv){
check[nx][ny]=true;
q.push(make_pair(nx, ny));
}
}
q.pop();
}
return false;
}
int main()
{
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int i, j;
cin >> n;
in = 99999;
ax = -99999;
for (i = 1; i <= n; i++)
{
for (j = 1; j <= n; j++)
{
cin >> arr[i][j];
in = min(in, arr[i][j]);
ax = max(ax, arr[i][j]);
}
}
int left = in;
int right = in;
int ans = 99999;
while (left <= right && right <= ax)
{
if (cross(left, right))
{
ans = min(ans, right - left);
left++;
}
else
right++;
}
cout << ans;
return 0;
}