fork download
  1. #include <iostream>
  2. #include<queue>
  3. using namespace std;
  4. struct node{
  5. int i,j;
  6. };
  7. int main() {
  8. int t;
  9. cin>>t;
  10. while(t--){
  11. queue<node> q;
  12. int m,n,i,j;
  13. cin>>m>>n;
  14. string a[m+1];int b[m+1][n+1];
  15. for(i=0;i<m;i++)
  16. cin>>a[i];
  17. for(i=0;i<m;i++)
  18. for(j=0;j<n;j++)
  19. if(a[i][j]=='1')
  20. {
  21. node temp;
  22. temp.i=i;
  23. temp.j=j;
  24. q.push(temp);
  25. b[i][j]=0;
  26. }
  27. while(!q.empty()){
  28. node temp=q.front();
  29. i=temp.i;j=temp.j;
  30. q.pop();
  31. if(i<m-1&&a[i+1][j]=='0'){
  32. a[i+1][j]=(b[i][j]+1)+48;
  33. b[i+1][j]=b[i][j]+1;
  34. temp.i=i+1;temp.j=j;
  35. q.push(temp);
  36. }
  37. if(i>0&&a[i-1][j]=='0'){
  38. a[i-1][j]=(b[i][j]+1)+48;
  39. b[i-1][j]=b[i][j]+1;
  40. temp.i=i-1;temp.j=j;
  41. q.push(temp);
  42. }
  43. if(j>0&&a[i][j-1]=='0'){
  44. a[i][j-1]=(b[i][j]+1)+48;
  45. b[i][j-1]=b[i][j]+1;
  46. temp.i=i;temp.j=j-1;
  47. q.push(temp);
  48. }
  49. if(j<n-1&&a[i][j+1]=='0'){
  50. a[i][j+1]=(b[i][j]+1)+48;
  51. b[i][j+1]=b[i][j]+1;
  52. temp.i=i;temp.j=j+1;
  53. q.push(temp);
  54. }
  55. }
  56. for(i=0;i<m;i++){
  57. for(j=0;j<n;j++){
  58. cout<<b[i][j];
  59. if(j!=n-1)
  60. cout<<" ";
  61. }
  62. cout<<endl;
  63. }
  64.  
  65.  
  66.  
  67. }
  68. return 0;
  69. }
  70.  
  71.  
Success #stdin #stdout 0s 2880KB
stdin
1
3 4
0001
0011
0110
stdout
3 2 1 0
2 1 0 0
1 0 0 1