-
Notifications
You must be signed in to change notification settings - Fork 5
/
UVA-1600.cpp
74 lines (68 loc) · 1.31 KB
/
UVA-1600.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
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
int m, n, k;
int graph[22][22];
int dist[22][22];
struct Node {
int x, y;
int num, ti;
};
int step1[4] = {1, 0, -1, 0};
int step2[4] = {0, 1, 0, -1};
void bfs() {
int i, j, x, y;
memset(dist, 0, sizeof(dist));
queue<Node> qu;
Node no1, no2 = {0, 0, 0, 0};
qu.push(no2);
while(!qu.empty()) {
no1 = qu.front();
qu.pop();
// printf("%d %d %d %d\n", no1.x, no1.y, no1.ti, no1.num);
for(i = 0; i < 4; ++i) {
x = no1.x + step1[i];
y = no1.y + step2[i];
if(x < 0 || x >= m) continue;
if(y < 0 || y >= n) continue;
if(x == m-1 && y == n-1) {
dist[m-1][n-1] = no1.num + 1;
return;
}
if(dist[x][y] != 0 && dist[x][y] < no1.num+1) continue;
if(graph[x][y] && no1.ti+1 > k) continue;
dist[x][y] = no1.num+1;
if(graph[x][y]) {
qu.push({x, y, no1.num+1, no1.ti+1});
} else {
qu.push({x, y, no1.num+1, 0});
}
}
}
return;
}
int main() {
int t;
int i, j;
scanf("%d", &t);
while(t--) {
scanf("%d %d %d", &m ,&n, &k);
for(i = 0; i < m; ++i) {
for( j = 0; j < n; ++j) {
scanf("%d", &graph[i][j]);
}
}
if(m == 1 && n == 1) {
printf("0\n");
continue;
}
bfs();
if(dist[m-1][n-1] == 0) {
printf("-1\n");
} else {
printf("%d\n", dist[m-1][n-1]);
}
}
return 0;
}