Qiuqiqiu  
不管道路多么崎岖坎坷,我永远不停下追逐梦想的脚步!

http://acm.hdu.edu.cn/showproblem.php?pid=2531

BFS

View Code
 1 #include <cstdio>
2 #include <cstring>
3 #include <queue>
4 using namespace std;
5 const int N=110;
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];
10 int px[10010],py[10010];
11 int n,m,pn;
12 struct node
13 {
14 int x,y,dis;
15 };
16 queue<node> q;
17 int ok(int xx,int yy)
18 {
19 int i,x,y;
20 for (i=1;i<=pn;i++)
21 {
22 x=xx+px[i]; y=yy+py[i];
23 if (x<1 || x>n || y<1 || y>m || maze[x][y]=='O')
24 return 0;
25 }
26 return 1;
27 }
28 int kill(int x,int y)
29 {
30 int i;
31 for (i=1;i<=pn;i++)
32 if (maze[x+px[i]][y+py[i]]=='Q') return 1;
33 return 0;
34 }
35 int bfs(int x,int y)
36 {
37 while (!q.empty()) q.pop();
38 vis[x][y]=1;
39 node u={x,y,0};
40 q.push(u);
41 while (!q.empty())
42 {
43 u=q.front(); q.pop();
44 int x,y,dis,d,nx,ny;
45 x=u.x; y=u.y; dis=u.dis;
46 for (d=0;d<4;d++)
47 {
48 nx=x+dx[d]; ny=y+dy[d];
49 if (vis[nx][ny] || !ok(nx,ny)) continue;
50 vis[nx][ny]=1;
51 node v={nx,ny,dis+1};
52 q.push(v);
53 if (kill(v.x,v.y)) return v.dis;
54 }
55 }
56 return -1;
57 }
58 int main()
59 {
60 int i,j,ans,x,y;
61 while (scanf("%d%d",&n,&m),n||m)
62 {
63 memset(vis,0,sizeof(vis));
64 memset(maze,0,sizeof(maze));
65 for (i=1;i<=n;i++) scanf("%s",maze[i]+1);
66 int flag=0; pn=0;
67 for (i=1;i<=n;i++) for (j=1;j<=m;j++)
68 if (maze[i][j]=='D')
69 {
70 if (!flag)
71 {
72 flag=1;
73 x=i; y=j;
74 }
75 pn++;
76 px[pn]=i-x; py[pn]=j-y;
77 }
78 ans=bfs(x,y);
79 if (ans<0) printf("Impossible\n");
80 else printf("%d\n",ans);
81 }
82 return 0;
83 }

 

posted on 2012-02-12 21:13  Qiuqiqiu  阅读(344)  评论(0编辑  收藏  举报