Description
Input is the matrix A of N by N non-negative integers.
A distance between two elements Aij and Apq 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 Aij and Apq 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 N2 integers, representing the matrix row-by-row.
Output
Output must contain N2 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
【题意】n*n的矩阵,对于不是0的地方仍为原值,是0的地方,找出离他最近的不是零的地方,如果有离他一样近的两个及以上地方就仍为0,就一个的话,为那一个的值。
【思路】巧用int dx[]= {1,1,-1,-1},cx[]= {-1,0,1,0};int dy[]= {1,-1,-1,1},cy[]= {0,1,0,-1};
还有判定条件if(k>n) return 0;
参考资料:http://blog.csdn.net/code_or_code/article/details/26274451
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; const int N=222; int mp[N][N]; int n; int dx[]= {1,1,-1,-1},cx[]= {-1,0,1,0}; int dy[]= {1,-1,-1,1},cy[]= {0,1,0,-1}; bool go(int x,int y) { if(x<1||x>n||y<1||y>n) return false; else return true; } int bfs(int x,int y,int k) { if(k>n) return 0; if(n==1||mp[x][y]) return mp[x][y]; int cnt=0,flag=0; int xx,yy; int tmpx,tmpy; for(int i=0; i<4; i++) { xx=x+k*cx[i]; yy=y+k*cy[i]; for(int j=0; j<k; j++) { if(mp[xx][yy]&&go(xx,yy)) { if(cnt==1) { flag=1; break; } cnt++; tmpx=xx,tmpy=yy; } xx+=dx[i]; yy+=dy[i]; } if(flag) break; } if(cnt==0) return bfs(x,y,k+1); else if(flag) return 0; else return mp[tmpx][tmpy]; } int main() { scanf("%d",&n); for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { scanf("%d",&mp[i][j]); } } for(int i=1; i<=n; i++) { for(int j=1; j<=n; j++) { printf("%d ",bfs(i,j,1)); } printf(" "); } return 0; }