EOJ-1104 bitmap

http://acm.cs.ecnu.edu.cn/problem.php?problemid=1104

题意:给一张只有1和0的图,求图上所有'0'的点到'1'的点的最短距离.

解法:若对每个0进行BFS到1的距离会超时,故从每个1进行BFS,更新到每个0的距离,可假象有一个源点连接着所有的1,从该源点进行BFS的搜索就可以达成一遍BFS更新所有0,方法即 先将所有1的点入队后,再进行BFS。

 1 #include<map>
 2 #include<set>
 3 #include<list>
 4 #include<cmath>
 5 #include<ctime>
 6 #include<queue>
 7 #include<stack>
 8 #include<cctype>
 9 #include<cstdio>
10 #include<string>
11 #include<vector>
12 #include<cstdlib>
13 #include<cstring>
14 #include<iostream>
15 #include<algorithm>
16 using namespace std;
17 const int maxn=185;
18 struct node{
19     int x,y;
20 }Q[maxn*maxn];                    //队列
21 int n,m;
22 int dir[][2]={1,0,-1,0,0,1,0,-1};
23 char mat[maxn][maxn];            //存图
24 int ret[maxn][maxn];            //存答案
25 int f,r;
26 int fit(int x,int y){
27     return x>=0 && x<n && y>=0 && y<m;        
28 }
29 void bfs(){
30     node p,q;
31     int cur=0;
32     while(f<r){
33         q=Q[f++];
34         cur=ret[q.x][q.y];
35         for(int i=0;i<4;i++){
36             p.x=q.x+dir[i][0];
37             p.y=q.y+dir[i][1];
38             if(fit(p.x,p.y) && mat[p.x][p.y]=='0' && ret[p.x][p.y]==0){
39                 ret[p.x][p.y]=cur+1;
40                 Q[r++]=p;
41             }
42         }
43     }
44 }
45 int main(){
46     while(~scanf("%d%d",&n,&m)){
47         for(int i=0;i<n;i++)
48             scanf("%s",mat[i]);
49         memset(ret,0,sizeof(ret));            //初始化
50         f=r=0;
51         for(int i=0;i<n;i++)
52             for(int j=0;j<m;j++)
53                 if(mat[i][j]=='1'){
54                     Q[r].x=i;                //将所有的1入队列
55                     Q[r++].y=j;
56                 }
57         bfs();
58         for(int i=0;i<n;i++)
59             for(int j=0;j<m;j++){
60                 printf("%d",ret[i][j]);
61                 if(j==m-1)printf("
");
62                 else printf(" ");
63             }
64     }
65     return 0;
66 }
View Code
原文地址:https://www.cnblogs.com/KimKyeYu/p/3185018.html