BZOJ2252 [2010Beijing wc]矩阵距离
2252: [2010Beijing wc]矩阵距离
Time Limit: 10 Sec Memory Limit: 256 MBSubmit: 624 Solved: 304
[Submit][Status][Discuss]
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
0001
0011
0110
Sample Output
3 2 1 0
2 1 0 0
1 0 0 1
2 1 0 0
1 0 0 1
HINT
对于100%的数据,满足 0 < m n <=1000
Source
【题解】
题面凑活着看吧。
还是需要一点小小的转换。
min(dist(A[i][j],A[x][y])其实就是(i,j)到最近的'1'的点的曼哈顿距离
BFS即可
初始状态是所有为1的点
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <iostream> 2 #include <cstdio> 3 #include <cstdlib> 4 #include <cstring> 5 #include <queue> 6 7 const int MAXN = 1000 + 10; 8 const int MAXM = 1000 + 10; 9 const int dx[4] = {0,0,1,-1}; 10 const int dy[4] = {1,-1,0,0}; 11 12 inline void read(int &x) 13 { 14 x = 0;char ch = getchar(), c = ch; 15 while(ch < '0' || ch > '9')c = ch, ch = getchar(); 16 while(ch <= '9' &&ch >= '0')x = x * 10 + ch - '0', ch = getchar(); 17 if(c == '-')x = -x; 18 } 19 20 int n,m,g[MAXN][MAXM],ans[MAXN][MAXM],b[MAXN][MAXM]; 21 char s[MAXM]; 22 23 struct Node 24 { 25 int x, y; 26 Node(int xx, int yy){x = xx;y = yy;} 27 Node(){} 28 }; 29 30 std::queue<Node> q; 31 32 void bfs() 33 { 34 register Node tmp; 35 register int xx, yy; 36 while(q.size()) 37 { 38 tmp = q.front();q.pop(); 39 for(register int i = 0;i < 4;++ i) 40 { 41 xx = tmp.x + dx[i], yy = tmp.y + dy[i]; 42 if(xx < 1 || yy < 1 || xx > n || yy > m || b[xx][yy])continue; 43 ans[xx][yy] = ans[tmp.x][tmp.y] + 1; 44 b[xx][yy] = 1; 45 q.push(Node(xx, yy)); 46 } 47 } 48 } 49 50 int main() 51 { 52 read(n), read(m); 53 for(register int i = 1;i <= n;++ i) 54 { 55 scanf("%s", s + 1); 56 for(register int j = 1;j <= m;++ j) 57 { 58 g[i][j] = s[j] - '0'; 59 if(g[i][j]) 60 { 61 b[i][j] = 1; 62 q.push(Node(i,j)); 63 } 64 } 65 } 66 bfs(); 67 for(register int i = 1;i <= n;++ i) 68 { 69 for(register int j = 1;j <= m;++ j) 70 printf("%d ", ans[i][j]); 71 putchar('\n'); 72 } 73 return 0; 74 }