AOJ 0558 Cheese(BFS)

又遇到一个很坑的问题,坑了我很久(想哭!):输出时,printf("%d\n",ans); 少了一个换行,结果结果错误,我太难了!!!

整体思路很简单,求出源节点到1,1到2,... n-1到n的最短花费,加起来就可以,即n次bfs就可以了。

 1 #include<cstring>
 2 #include<iostream>
 3 #include<queue>
 4 #include<algorithm>
 5 #include<cstdio>
 6 
 7 using namespace std;
 8 
 9 typedef pair<int,int> P;
10 const int INF=100000000;
11 int h,w,n;
12 char maze[1005][1005];
13 int d[1005][1005];
14 int dx[4]={1,-1,0,0};
15 int dy[4]={0,0,-1,1};
16 int ans;
17 
18 int bfs(char charstart,char charend){
19     int x,y;
20     for(int i=0;i<h;i++){
21         for(int j=0;j<w;j++){
22             if(maze[i][j]==charstart){
23                 x=i;y=j;
24             }
25         }
26     }
27     queue<P> que;
28     que.push(P(x,y));
29     while(que.size()){
30         x=que.front().first;
31         y=que.front().second;
32         que.pop();
33         if(maze[x][y]==charend){
34             return d[x][y];
35         }
36         for(int i=0;i<4;i++){
37             int nx=x+dx[i],ny=y+dy[i];
38             if(0<=nx&&nx<h&&ny>=0&&ny<w&&d[nx][ny]==0&&maze[nx][ny]!='X'){
39                 d[nx][ny]=d[x][y]+1;
40                 que.push(P(nx,ny));
41             }
42         }
43     }
44 }
45 
46 void solve(){
47     scanf("%d%d%d",&h,&w,&n);
48     for(int i=0;i<h;i++){
49         for(int j=0;j<w;j++){
50             cin >> maze[i][j];
51         }
52     }
53     ans+=bfs('S','1');
54     for(int i=1;i<=n-1;i++){
55         memset(d,0,sizeof(d));
56         char s = char(i+48);
57         char e = char(i+1+48);
58         ans+=bfs(s,e);
59     }
60     printf("%d\n",ans);
61 }
62 
63 int main(){
64     solve();
65     return 0;
66 }

猜你喜欢

转载自www.cnblogs.com/xiaoxb17/p/11808573.html