BZOJ 2252: [2010Beijing wc]矩阵距离

题目

2252: [2010Beijing wc]矩阵距离

Time Limit: 10 Sec  Memory Limit: 256 MB

Description

 

假设我们有矩阵,其元素值非零即1

a11…… a1m

…………….

an1…….anm

 

定义aij与akl之间的距离为D(aij,akl)=abs(i-k)+abs(j-L) 

Input

输入文件的第一行为两个整数,分别代表n和m。 
接下来的n行,第i行的第 j个字符代表aij

Output

输出包含N行,每行M个用空格分开的数字,其中第i行第J个数字代表
Min(D(aij,axy) 1<=x<=N 1<=y<m,且axy=1

Sample Input

3 4
0001
0011
0110

Sample Output

3 2 1 0
2 1 0 0
1 0 0 1

HINT

 

对于100%的数据,满足 0 <  m n <=1000

题解

好吧,就是一个宽搜,而且根据宽搜的性质,所以每个点只需要经过一次就足够了。

代码

 1 /*Author:WNJXYK*/
 2 #include<cstdio>
 3 #include<queue>
 4 using namespace std;
 5 
 6 int dist[1005][1005];
 7 
 8 int n,m;
 9 int dx[]={0,1,0,-1,0};
10 int dy[]={0,0,1,0,-1};
11 inline char read(){
12     char x;
13     x=getchar();
14     while(x!='1' && x!='0') x=getchar();
15     return x;
16 }
17 struct xy{
18     int x,y;
19     xy(){}
20     xy(int a,int b){
21         x=a;y=b;
22     }
23 };
24 queue<xy> que;
25 
26 inline void bfs(){
27     
28     while(!que.empty()){
29         int x=que.front().x,y=que.front().y;
30         que.pop();
31         for (int k=1;k<=4;k++){
32             int nx=x+dx[k],ny=y+dy[k];
33             if (nx<1 || nx>n || ny<1 || ny>m || dist[nx][ny]!=-1) continue;
34             dist[nx][ny]=dist[x][y]+1;
35             que.push(xy(nx,ny));
36         }    
37     }
38     
39 } 
40 int main(){
41     scanf("%d%d",&n,&m);
42     for (int i=1;i<=n;i++){
43         for (int j=1;j<=m;j++){
44             if (read()=='0') dist[i][j]=-1; else {dist[i][j]=0;que.push(xy(i,j));}
45         }
46     }
47     bfs();
48     for (int i=1;i<=n;i++){
49         for (int j=1;j<=m;j++){
50             printf("%d ",dist[i][j]);
51         } 
52         printf("\n");
53     }
54     return 0;
55 }
View Code

 

posted @ 2014-12-13 19:33  WNJXYK  阅读(284)  评论(0编辑  收藏  举报

WNJXYK-我今年一定要努力!