http://acm.hdu.edu.cn/showproblem.php?pid=2364
BFS
我的代码
1 #include <cstdio>
2 #include <cstring>
3 #include <queue>
4 using namespace std;
5 const int N=100;
6 const int dx[4]={0,1,0,-1};
7 const int dy[4]={1,0,-1,0};
8 char maze[N][N];
9 int vis[N][N][4];
10 int n,m;
11 struct sta
12 {
13 int x,y,dir,dis;
14 };
15 queue<sta> q;
16 int bfs(int x,int y)
17 {
18 while (!q.empty()) q.pop();
19 sta u={x,y,-1};
20 q.push(u);
21 int dir;
22 while (!q.empty())
23 {
24 u=q.front(); q.pop();
25 x=u.x; y=u.y; dir=u.dir;
26 int d,dd,nx,ny;
27 int flag=0;
28 for (dd=0;dd<4;dd++)
29 {
30 if (dir<0) d=dd; else
31 switch (dd)
32 {
33 case 1: if (dir%2) d=0; else d=1; break;
34 case 2: d=d+2; break;
35 case 3: d=dir; break;
36 default: continue; break;
37 }
38 if (flag && d==dir) continue;
39 nx=x+dx[d]; ny=y+dy[d];
40 if (maze[nx][ny]=='#') continue;
41 flag=1;
42 if (vis[nx][ny][d]) continue;
43 vis[nx][ny][d]=1;
44 sta v={nx,ny,d,u.dis+1};
45 if (nx==1 || nx==n || ny==1 || ny==m) return v.dis;
46 q.push(v);
47 }
48 }
49 return -1;
50 }
51 int main()
52 {
53 int T;
54 scanf("%d",&T);
55 int i,j,x,y,ans;
56 while (T--)
57 {
58 scanf("%d%d",&n,&m);
59 memset(vis,0,sizeof(vis));
60 memset(maze,0,sizeof(maze));
61 for (i=1;i<=n;i++) scanf("%s",maze[i]+1);
62 for (i=1;i<=n;i++)
63 for (j=1;j<=m;j++)
64 if (maze[i][j]=='@') {x=i; y=j;}
65 if (x==1 || x==n || y==1 || y==m) ans=0;
66 else ans=bfs(x,y);
67 printf("%d\n",ans);
68 }
69 return 0;
70 }