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

  1. 3
  2. 0 0 0
  3. 1 0 2
  4. 0 3 0

Sample Output

  1. 1 0 2
  2. 1 0 2
  3. 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

  1. #include<iostream>
  2. #include<stdio.h>
  3. #include<string.h>
  4. using namespace std;
  5. const int N=;
  6. int mp[N][N];
  7. int n;
  8. int dx[]= {,,-,-},cx[]= {-,,,};
  9. int dy[]= {,-,-,},cy[]= {,,,-};
  10. bool go(int x,int y)
  11. {
  12. if(x<||x>n||y<||y>n) return false;
  13. else return true;
  14. }
  15. int bfs(int x,int y,int k)
  16. {
  17. if(k>n) return ;
  18. if(n==||mp[x][y]) return mp[x][y];
  19. int cnt=,flag=;
  20. int xx,yy;
  21. int tmpx,tmpy;
  22. for(int i=; i<; i++)
  23. {
  24. xx=x+k*cx[i];
  25. yy=y+k*cy[i];
  26. for(int j=; j<k; j++)
  27. {
  28. if(mp[xx][yy]&&go(xx,yy))
  29. {
  30. if(cnt==)
  31. {
  32. flag=;
  33. break;
  34. }
  35. cnt++;
  36. tmpx=xx,tmpy=yy;
  37. }
  38. xx+=dx[i];
  39. yy+=dy[i];
  40.  
  41. }
  42. if(flag) break;
  43. }
  44. if(cnt==) return bfs(x,y,k+);
  45. else if(flag) return ;
  46. else return mp[tmpx][tmpy];
  47. }
  48. int main()
  49. {
  50. scanf("%d",&n);
  51. for(int i=; i<=n; i++)
  52. {
  53. for(int j=; j<=n; j++)
  54. {
  55. scanf("%d",&mp[i][j]);
  56. }
  57. }
  58. for(int i=; i<=n; i++)
  59. {
  60. for(int j=; j<=n; j++)
  61. {
  62. printf("%d ",bfs(i,j,));
  63. }
  64. printf("\n");
  65. }
  66. return ;
  67. }