fork(1) download
  1. #include<bits/stdc++.h>
  2. #define ll long long
  3. using namespace std;
  4. int main(){
  5. ios_base::sync_with_stdio(false);
  6. int t;
  7. cin>>t;
  8. while(t--)
  9. {
  10. int n,m;
  11. char c;
  12. queue<int>q;
  13. cin>>n>>m;
  14. int a[n][m]={0};
  15. for (int i=0;i<n;++i){
  16. for (int j=0;j<m;++j)
  17. {
  18. char c;
  19. cin>>c;
  20. //make a queue for all the co-ordinates with value 1;
  21. if(c=='1')
  22. {
  23. a[i][j]=0;
  24. q.push(i);
  25. q.push(j);
  26. }
  27. else
  28. a[i][j]=INT_MAX;
  29. }
  30. }
  31. while(!q.empty())
  32. {
  33. int x=q.front();q.pop();
  34. int y=q.front();q.pop();
  35. //incease in all possible directions ^,↓,↔
  36. int dist=a[x][y]+1;
  37. //up
  38. if(x-1>=0&&dist<a[x-1][y])
  39. a[x-1][y]=dist;q.push(x-1);q.push(y);
  40. //down
  41. if(x+1<n&&dist<a[x+1][y])
  42. a[x+1][y]=dist;q.push(x+1);q.push(y);
  43. //left
  44. if(y-1>=0&&dist<a[x][y-1])
  45. a[x][y-1]=dist;q.push(x);q.push(y-1);
  46. //right
  47. if(y+1<m&&dist<a[x][y+1])
  48. a[x][y+1]=dist;q.push(x);q.push(y+1);
  49. }
  50. for (int i=0;i<n;++i)
  51. {
  52. for (int j=0;j<m;++j)
  53. {
  54. cout<<a[i][j]<<" ";
  55. cout<<endl;
  56. }
  57. }
  58. cout<<endl;
  59. }
  60. return 0;
  61. }
Runtime error #stdin #stdout 0s 4560KB
stdin
1
3 4
0001
0011
0110
stdout
Standard output is empty