TIOJ 1143. 4.靈犬尋寶

TIOJ-1025

BFS
我也不知道為啥寫得這麼醜,可能跟我一樣吧

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
#include<bits/stdc++.h>
struct Case{
int x, y, t;
};
Case C[10005];
int m[105][105], c[105][105];
int main(){
int n, x, y, bx, by, top=0, bot=0 ,a ,b;
scanf("%d", &n);
for(int i=0; i<n; i++){
scanf("%d%d", &a, &b);
m[a+3][b+3] = 1;
}
scanf("%d%d", &x, &y);
scanf("%d%d", &bx, &by);
bx+=3;
by+=3;
C[top].x = x+3;
C[top].y = y+3;
C[top].t = 0;
bot++;
memset(c, 0, sizeof(c));
while((C[top].x!=bx||C[top].y!=by)&&top!=bot){
if(!(C[top].x<3||C[top].x>102||C[top].y<3||C[top].y>102)){
if(!m[C[top].x+1][C[top].y]){
if(!c[C[top].x+3][C[top].y+1]&&!m[C[top].x+3][C[top].y+1]){
c[C[top].x+3][C[top].y+1]++;
C[bot].x = C[top].x+3;
C[bot].y = C[top].y+1;
C[bot].t = C[top].t+1;
bot++;
}
if(!c[C[top].x+3][C[top].y-1]&&!m[C[top].x+3][C[top].y-1]){
c[C[top].x+3][C[top].y-1]++;
C[bot].x = C[top].x+3;
C[bot].y = C[top].y-1;
C[bot].t = C[top].t+1;
bot++;
}
}
if(!m[C[top].x-1][C[top].y]){
if(!c[C[top].x-3][C[top].y+1]&&!m[C[top].x-3][C[top].y+1]){
c[C[top].x-3][C[top].y+1]++;
C[bot].x = C[top].x-3;
C[bot].y = C[top].y+1;
C[bot].t = C[top].t+1;
bot++;
}
if(!c[C[top].x-3][C[top].y-1]&&!m[C[top].x-3][C[top].y-1]){
c[C[top].x-3][C[top].y-1]++;
C[bot].x = C[top].x-3;
C[bot].y = C[top].y-1;
C[bot].t = C[top].t+1;
bot++;
}
}
if(!m[C[top].x][C[top].y+1]){
if(!c[C[top].x+1][C[top].y+3]&&!m[C[top].x+1][C[top].y+3]){
c[C[top].x+1][C[top].y+3]++;
C[bot].x = C[top].x+1;
C[bot].y = C[top].y+3;
C[bot].t = C[top].t+1;
bot++;
}
if(!c[C[top].x-1][C[top].y+3]&&!m[C[top].x-1][C[top].y+3]){
c[C[top].x-1][C[top].y+3]++;
C[bot].x = C[top].x-1;
C[bot].y = C[top].y+3;
C[bot].t = C[top].t+1;
bot++;
}
}
if(!m[C[top].x][C[top].y-1]){
if(!c[C[top].x+1][C[top].y-3]&&!m[C[top].x+1][C[top].y-3]){
c[C[top].x+1][C[top].y-3]++;
C[bot].x = C[top].x+1;
C[bot].y = C[top].y-3;
C[bot].t = C[top].t+1;
bot++;
}
if(!c[C[top].x-1][C[top].y-3]&&!m[C[top].x-1][C[top].y-3]){
c[C[top].x-1][C[top].y-3]++;
C[bot].x = C[top].x-1;
C[bot].y = C[top].y-3;
C[bot].t = C[top].t+1;
bot++;
}
}
}
top++;
}
if(C[top].t==0) printf("impossible\n");
else printf("%d\n", C[top].t);
}