题目链接:fzu1408 hnu10109 代码:bfs (多源的宽度优先搜索) 见书218页 //1<=n,m<=182 #include <iostream> #include <queue> using namespace std; int map[190][190]; //存储各点到最近的白点的步数 int n,m; int move[4][2]={-1,0,0,-1,1,0,0,1}; struct node { int x,y,step;}tmp,front; //x,y,step 用于记录坐标和走的步数 queue <node> list; void bfs() { while(!list.empty()) { front=list.front(); list.pop(); tmp.step=front.step+1; for(int u=0;u<4;u++) { tmp.x=front.x+move[u][0]; tmp.y=front.y+move[u][1]; if(tmp.x>=0&&tmp.x<n&&tmp.y>=0&&tmp.y<m) if(map[tmp.x][tmp.y]==-1) { map[tmp.x][tmp.y]=tmp.step;list.push(tmp);} } } } int main(int argc, char *argv[]) { char ch; int i,j; while(cin>>n>>m) { for(i=0;i<n;i++) for( j=0;j<m;j++) { cin>>ch;map[i][j]=-1; if(ch=='1') { tmp.x=i,tmp.y=j;tmp.step=0; list.push(tmp); map[i][j]=0; } } bfs(); for(i=0;i<n;i++) for(j=0;j<m;j++) if(j<m-1)cout<<map[i][j]<<' '; else cout<<map[i][j]<<endl; } return 0; }