fork(3) download
  1. #include <iostream>
  2. #include <stdio.h>
  3. #include <string.h>
  4. #include <vector>
  5. #include <algorithm>
  6. #include <time.h>
  7. #include <queue>
  8. #define mod 1000000000
  9. #define ll long long int
  10.  
  11. using namespace std;
  12.  
  13. class point
  14. {
  15. public:
  16. int x, y, z;
  17. point(int i, int j, int k)
  18. {
  19. x = i;
  20. y = j;
  21. z = k;
  22. }
  23. };
  24.  
  25. int n, m;
  26. int grid[200][200];
  27. char board[200][200];
  28.  
  29. int dx[] = {1, -1, 0, 0};
  30. int dy[] = {0, 0, 1, -1};
  31.  
  32. void BFS(queue <point> bfs)
  33. {
  34. int i, j, x, y;
  35. point temp(0,0,0);
  36. while(!bfs.empty())
  37. {
  38. temp = bfs.front();
  39. bfs.pop();
  40. grid[temp.x][temp.y] = temp.z;
  41.  
  42. // if the adjacent cells are unvisited, pushing it onto the queue.
  43. for(i=0; i<4; i++)
  44. {
  45. x = temp.x+dx[i];
  46. y = temp.y+dy[i];
  47. if(grid[x][y]==-1)
  48. bfs.push(point(x,y,temp.z+1));
  49. }
  50. }
  51. for(i=0; i<n; i++)
  52. {
  53. for(j=0; j<m; j++)
  54. printf("%d ", grid[i][j]);
  55. printf("\n");
  56. }
  57. }
  58.  
  59. int main()
  60. {
  61. int t, i, j;
  62. scanf("%d", &t);
  63. while(t--)
  64. {
  65. queue <point> bfs;
  66.  
  67. // taking input
  68. scanf("%d %d", &n, &m);
  69. for(i=0; i<n; i++)
  70. scanf("%s", board[i]);
  71.  
  72. // putting the value for each point to be -1
  73. for(i=0; i<n; i++)
  74. for(j=0; j<m; j++)
  75. grid[i][j] = -1;
  76.  
  77. for(i=0; i<n; i++)
  78. {
  79. for(j=0; j<m; j++)
  80. {
  81. // if the point is white, putting its value to be 1, and pushing it onto the queue
  82. if(board[i][j]=='1')
  83. {
  84. grid[i][j] = 0;
  85. bfs.push(point(i,j,0));
  86. }
  87. }
  88. }
  89. BFS(bfs);
  90. }
  91. return 0;
  92. }
  93.  
  94.  
Success #stdin #stdout 0s 3628KB
stdin
1
3 4
0001
0011
0110
stdout
3 2 1 0 
2 1 0 0 
1 0 0 1