問題 I: 矩陣距離
時間限制: 1 Sec 內存限制: 128 MB提交: 15 解決: 7
[提交] [狀態] [命題人:admin]
題目描述
給定一個N行M列的01矩陣 A,A[i][j] 與 A[k][l] 之間的曼哈頓距離定義為:
dist(A[i][j],A[k][l])=|i-k|+|j-l|
輸出一個N行M列的整數矩陣B,其中:
B[i][j]=min(1≤x≤N,1≤y≤M,A[x][y]=1){dist(A[i][j],A[x][y])}
即求與每個位置曼哈頓距離最近的1
N,M≤1000。
dist(A[i][j],A[k][l])=|i-k|+|j-l|
輸出一個N行M列的整數矩陣B,其中:
B[i][j]=min(1≤x≤N,1≤y≤M,A[x][y]=1){dist(A[i][j],A[x][y])}
即求與每個位置曼哈頓距離最近的1
N,M≤1000。
輸入
第一行兩個整數n,m(0 <m,n <=1000)。
接下來一個N行M列的01矩陣,數字之間沒有空格。
接下來一個N行M列的01矩陣,數字之間沒有空格。
輸出
一個N行M列的矩陣B,相鄰兩個整數之間用一個空格隔開。
樣例輸入
3 4
0001
0011
0110
樣例輸出
3 2 1 0
2 1 0 0
1 0 0 1
#include <bits/stdc++.h> using namespace std; const int maxn=1100; struct node{ int x,y; }; int sx[8]={0,1,-1,0,0},sy[8]={0,0,0,1,-1},n,m,dis[maxn][maxn],p[maxn][maxn]; queue<node>q; int main() { scanf("%d%d",&n,&m); char temp; for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ while( ( temp = getchar() ) != '1' && temp != '0' ); p[i][j]=temp-'0'; dis[i][j]=-1; if(p[i][j]){ q.push(node{i,j}); dis[i][j]=0; } } } /*for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ cout<<p[i][j]<<' '; } cout<<endl; }*/ while(q.size()){ node cur=q.front(); q.pop(); for(int i=1;i<=4;i++){ int dx=cur.x+sx[i],dy=cur.y+sy[i]; if(dx>=1&&dx<=n&&dy>=1&&dy<=m&&dis[dx][dy]==-1){ dis[dx][dy]=dis[cur.x][cur.y]+1; q.push(node{dx,dy}); } } } for(int i=1;i<=n;i++){ for(int j=1;j<=m;j++){ if(j!=1) cout<<' '; cout<<dis[i][j]; } cout<<endl; } return 0; }
