-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspiderman.cpp
103 lines (73 loc) · 1.63 KB
/
spiderman.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include <bits/stdc++.h>
using namespace std;
struct cell {
int h;
int d;
cell () {
d = -1;
}
};
struct qCell
{
int x;
int y;
qCell() {
}
qCell(int x, int y) {
this->x = x;
this->y = y;
}
};
bool operator== (qCell a, qCell b) {
return a.x == b.x && a.y == b.y;
}
int main()
{
int t;
cin >> t;
while (t--) {
int m, n, x, y, d;
cin >> m >> n >> x >> y >> d;
cell arr[m][n];
for (int i = 0; i < m; i++ ) {
for (int j = 0; j < n; j++ ) {
cin >> arr[i][j].h;
}
}
qCell tmp;
tmp.x = 0;
tmp.y = 0;
arr[tmp.x][tmp.y].d = 0;
queue<qCell> q;
q.push(tmp);
qCell target;
target.x = x - 1;
target.y = y - 1;
int result = -1;
while(q.size()) {
qCell f = q.front();
q.pop();
if (f == target) {
result = arr[f.x][f.y].d;
}
if (f.x + 1 < m && arr[f.x + 1][f.y].d == -1 && abs(arr[f.x][f.y].h - arr[f.x + 1][f.y].h) <= d ) {
q.push(qCell(f.x + 1, f.y));
arr[f.x + 1][f.y].d = arr[f.x][f.y].d + 1;
}
if (f.x - 1 >= 0 && arr[f.x - 1][f.y].d == -1 && abs(arr[f.x][f.y].h - arr[f.x - 1][f.y].h) <= d ) {
q.push(qCell(f.x - 1, f.y));
arr[f.x - 1][f.y].d = arr[f.x][f.y].d + 1;
}
if (f.y + 1 < n && arr[f.x][f.y + 1].d == -1 && abs(arr[f.x][f.y].h - arr[f.x][f.y + 1].h) <= d ) {
q.push(qCell(f.x, f.y + 1));
arr[f.x][f.y + 1].d = arr[f.x][f.y].d + 1;
}
if (f.y - 1 >= 0 && arr[f.x][f.y - 1].d == -1 && abs(arr[f.x][f.y].h - arr[f.x][f.y - 1].h) <= d ) {
q.push(qCell(f.x, f.y - 1));
arr[f.x][f.y - 1].d = arr[f.x][f.y].d + 1;
}
}
cout << (result == -1 || result == 0 ? result : result - 1) << endl;
}
return 0;
}