poj 2312(bfs+priority_queue)

开始的时候想的是bfs。对于每个砖头step+2,然后wa了。看了discuss明白了。这样的话就相当于别的方向只走了一步,而砖头的这个方向是两步,不符合搜索的公平性。

然后把queue换成priority_queue就ac了。

数据:

8 10
YEEEEEBBBB
BBBEEEEEEE
BBBBBBEEEE
BBBBREEEEE
EEEEEEBBBB
BBBBBBBEEE
EEEEEEEEEE
BBBBBEEEET
17

10 10
YEEEEEBBBB
BBBEEEEEEE
BBBBBBEEEE
RRRRBBBBBE
BBEERSSSEE
BBBBREEEEE
EEEEEEBBBB
BBBBBBBEEE
EEEEEEEEEE
BBBBBEEEET
19

 

View Code
 1 // File Name: 2312.cpp
 2 // Author: Missa
 3 // Created Time: 2013/2/19 星期二 11:56:37
 4 
 5 #include<iostream>
 6 #include<cstdio>
 7 #include<cstring>
 8 #include<algorithm>
 9 #include<cmath>
10 #include<queue>
11 #include<stack>
12 #include<string>
13 #include<vector>
14 #include<cstdlib>
15 #include<map>
16 #include<set>
17 using namespace std;
18 #define CL(x,v) memset(x,v,sizeof(x));
19 const int dir[4][2]={-1,0,1,0,0,-1,0,1};
20 const int maxn = 305;
21 int n,m;
22 struct Point
23 {
24     int x,y;
25     int step;
26     Point(){}
27     Point(int x,int y,int step):x(x),y(y),step(step){}
28     bool operator <(const Point&a)const
29     {
30         return step>a.step;
31     }
32 };
33 char g[maxn][maxn];
34 bool vis[maxn][maxn];
35 int bfs(Point st)
36 {
37     priority_queue<Point>q;
38     while(!q.empty()) q.pop();
39     vis[st.x][st.y]=1;
40     q.push(st);
41     while(!q.empty())
42     {
43         Point cur=q.top();q.pop();
44         //cout<<cur.x<<" "<<cur.y<<endl; 
45         if(g[cur.x][cur.y]=='T') return cur.step;
46         for(int i=0;i<4;i++ )
47         {
48             Point nt;
49             nt.x=cur.x+dir[i][0];
50             nt.y=cur.y+dir[i][1];
51             nt.step=cur.step+1;
52             if(nt.x<=0 || nt.y<=0 || nt.x>n || nt.y>m) continue;
53             if(vis[nt.x][nt.y] || g[nt.x][nt.y]=='S' || g[nt.x][nt.y]=='R') continue;
54             if(g[nt.x][nt.y]=='B') nt.step++;
55             vis[nt.x][nt.y]=1;
56             q.push(nt);
57         }
58     }
59     return -1;
60 }
61 int main()
62 {
63     while(~scanf("%d%d",&n,&m))
64     {
65         if(!n && !m) break;
66         CL(g,0);
67         CL(vis,0);
68         for(int i=1;i<=n;i++)
69             scanf("%s",g[i]+1);
70         bool flag=0;
71         for(int i=1;i<=n;i++)
72         {
73             for(int j=1;j<=m;j++)
74             {
75                 if(g[i][j]=='Y')
76                 {
77                     printf("%d\n",bfs(Point(i,j,0)));
78                     flag=1;
79                     break;
80                 }
81             }
82             if(flag) break;
83         }
84     }
85     return 0;
86 }

 

posted @ 2013-02-19 16:09  Missa  阅读(199)  评论(0编辑  收藏  举报