Nearest number - 2
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 4262 | Accepted: 1325 |
Description
Input is the matrix A of N by N non-negative integers.
A distance between two elements A ij and A pq is defined as |i − p| + |j − q|.
Your program must replace each zero element in the matrix with the nearest non-zero one. If there are two or more nearest non-zeroes, the zero must be left in place.
Constraints
1 ≤ N ≤ 200, 0 ≤ Ai ≤ 1000000
A distance between two elements A ij and A pq is defined as |i − p| + |j − q|.
Your program must replace each zero element in the matrix with the nearest non-zero one. If there are two or more nearest non-zeroes, the zero must be left in place.
Constraints
1 ≤ N ≤ 200, 0 ≤ Ai ≤ 1000000
Input
Input contains the number N followed by N
2 integers, representing the matrix row-by-row.
Output
Output must contain N
2 integers, representing the modified matrix row-by-row.
Sample Input
3 0 0 0 1 0 2 0 3 0
Sample Output
1 0 2 1 0 2 0 3 0
Source
Northeastern Europe 2003, Far-Eastern Subregion
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include<iostream> #include<cmath> #include<cstring> #include<cstdio> #include<cstdlib> #include<algorithm> using namespace std; int n,map[210][210]; int ans[210][210],xx[4]={-1,-1,1,1},yy[4]={1,-1,-1,1}; int dfs(int x,int y) { int k,a; for(int i=1;i<2*n;i++)//到(x,y)的距离为i { k=0; if(y-i>0&&map[x][y-i]) {a=map[x][y-i];k++;} if(y+1<=n&&map[x][y+i]) {a=map[x][y+i];k++;} if(x-i>0&&map[x-i][y]) {a=map[x-i][y];k++;} if(x+i<=n&&map[x+i][y]) {a=map[x+i][y];k++;} if(k>1) return 0; for(int j=1;j<i;j++)//横坐标绝对值差j { for(int p=0;p<4;p++)//左上左下右上右下 { int xa=x+xx[p]*j,ya=y+yy[p]*(i-j); if(xa>0&&xa<=n&&ya>0&&ya<=n&&map[xa][ya]) {a=map[xa][ya];k++;} if(k>1) return 0; } } if(k==1) return a; } if(k==1) return a; else return 0; } int main() { scanf("%d",&n); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) scanf("%d",&map[i][j]); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) { if(map[i][j]==0) ans[i][j]=dfs(i,j); else ans[i][j]=map[i][j]; } } for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) printf("%d ",ans[i][j]); cout<<endl; } return 0; }