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
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=;
- int mp[N][N];
- int n;
- int dx[]= {,,-,-},cx[]= {-,,,};
- int dy[]= {,-,-,},cy[]= {,,,-};
- bool go(int x,int y)
- {
- if(x<||x>n||y<||y>n) return false;
- else return true;
- }
- int bfs(int x,int y,int k)
- {
- if(k>n) return ;
- if(n==||mp[x][y]) return mp[x][y];
- int cnt=,flag=;
- int xx,yy;
- int tmpx,tmpy;
- for(int i=; i<; i++)
- {
- xx=x+k*cx[i];
- yy=y+k*cy[i];
- for(int j=; j<k; j++)
- {
- if(mp[xx][yy]&&go(xx,yy))
- {
- if(cnt==)
- {
- flag=;
- break;
- }
- cnt++;
- tmpx=xx,tmpy=yy;
- }
- xx+=dx[i];
- yy+=dy[i];
- }
- if(flag) break;
- }
- if(cnt==) return bfs(x,y,k+);
- else if(flag) return ;
- else return mp[tmpx][tmpy];
- }
- int main()
- {
- scanf("%d",&n);
- for(int i=; i<=n; i++)
- {
- for(int j=; j<=n; j++)
- {
- scanf("%d",&mp[i][j]);
- }
- }
- for(int i=; i<=n; i++)
- {
- for(int j=; j<=n; j++)
- {
- printf("%d ",bfs(i,j,));
- }
- printf("\n");
- }
- return ;
- }