5 5 A.T.. .#..# ..... ####. ....B 1 5 A.T.B
8 -1思路:
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
104
105
106
107 |
#include <stdio.h> #include <string.h> int
n,m; typedef
struct
Node { int
x; int
y; }Node; char
map[111][111]; int
ans[111][111]; int
move[4][2]={{1,0},{0,-1},{-1,0},{0,1}}; int
bfs(Node a,Node b); int
main() { int
k; Node a,b; while ( scanf ( "%d%d" ,&n,&m)!=EOF) { memset (map, ‘#‘ , sizeof (map)); memset (ans,0, sizeof (ans)); int
i,j; for (i=1;i<=n;i++) scanf ( "%s" ,&map[i][1]); for (i=1;i<=n;i++) { for (j=1;j<=m;j++) { if (map[i][j]== ‘A‘ ) { a.x=i; a.y=j; } else
if (map[i][j]== ‘B‘ ) { b.x=i; b.y=j; } } } for (i=1;i<=n;i++) { for (j=1;j<=m;j++) { if (map[i][j]== ‘T‘ ) { if (map[i-1][j-1]!= ‘T‘ ) map[i-1][j-1]= ‘#‘ ; if (map[i-1][j]!= ‘T‘ ) map[i-1][j]= ‘#‘ ; if (map[i-1][j+1]!= ‘T‘ ) map[i-1][j+1]= ‘#‘ ; if (map[i][j+1]!= ‘T‘ ) map[i][j+1]= ‘#‘ ; if (map[i+1][j+1]!= ‘T‘ ) map[i+1][j+1]= ‘#‘ ; if (map[i+1][j]!= ‘T‘ ) map[i+1][j]= ‘#‘ ; if (map[i+1][j-1]!= ‘T‘ ) map[i+1][j-1]= ‘#‘ ; if (map[i][j-1]!= ‘T‘ ) map[i][j-1]= ‘#‘ ; } } } if (map[a.x][a.y]== ‘#‘ ||map[b.x][b.y]== ‘#‘ ) { printf ( "-1\n" ); continue ; } k=bfs(a,b); if (k) printf ( "%d\n" ,k); else printf ( "-1\n" ); } return
0; } int
bfs(Node a,Node b) { Node queue[100000]; ans[a.x][a.y]=0; int
i; int
front=0,rear=1; queue[front]=a; map[a.x][a.y]= ‘#‘ ; while (front<rear) { Node newl; for (i=0;i<4;i++) { newl.x=queue[front].x+move[i][0]; newl.y=queue[front].y+move[i][1]; if (newl.x>=1&&newl.x<=n&&newl.y>=1&&newl.y<=m&&map[newl.x][newl.y]!= ‘#‘ ) { map[newl.x][newl.y]= ‘#‘ ; ans[newl.x][newl.y]=ans[queue[front].x][queue[front].y]+1; queue[rear]=newl; if (newl.x==b.x&&newl.y==b.y) return
ans[b.x][b.y]; rear++; } } front++; } return
0; } |
原文:http://www.cnblogs.com/ahu-shu/p/3521507.html