fork download
  1. import java.io.*;
  2. import java.util.*;
  3. import java.lang.*;
  4.  
  5. class Main
  6. {
  7.  
  8. static class FastReader{
  9. public FastReader(){
  10. }
  11. String next(){
  12. while(st == null || !st.hasMoreElements()){
  13. try{
  14. st = new StringTokenizer(br.readLine());
  15. }
  16. catch(IOException e){
  17. e.printStackTrace();
  18. }
  19. }
  20. return st.nextToken();
  21. }
  22. int nextInt(){
  23. return Integer.parseInt(next());
  24. }
  25. long nextLong(){
  26. return Long.parseLong(next());
  27. }
  28. String nextLine(){
  29. String sr = "";
  30. try{
  31. sr = br.readLine();
  32. }
  33. catch(IOException e){
  34. e.printStackTrace();
  35. }
  36. return sr;
  37. }
  38. }
  39. public static class Node {
  40. int i ;
  41. int j;
  42. public Node(int i, int j) {
  43. super();
  44. this.i = i;
  45. this.j = j;
  46. }
  47.  
  48. }
  49. static int dirX[] = {-1,0,1};
  50. static int dirY[] = {-1,0,1};
  51. public static void main (String[] args) throws java.lang.Exception
  52. {
  53. FastReader ft = new FastReader();
  54. int t = ft.nextInt();
  55. while(t-->0)
  56. {
  57. int n = ft.nextInt();
  58. int m = ft.nextInt();
  59. int vis[][] = new int[n][m];
  60. char a[][] = new char[n][m];
  61. for(int i = 0;i < n;i++) {
  62. String s = ft.nextLine().trim().replace(" ", "");
  63. // System.out.println(s);
  64. a[i] = s.toCharArray();}
  65. Queue<Node> q = new LinkedList<>();
  66. for(int i = 0;i < n;i++)
  67. for(int j = 0;j < m;j++)
  68. {
  69. if(a[i][j] == '1')
  70. {
  71. q.add(new Node(i,j));
  72. vis[i][j] = 1;
  73. }
  74. }
  75. while(!q.isEmpty()) {
  76. Node node = q.poll();
  77. int x = node.i;
  78. int y = node.j;
  79. for(int i = 0;i <=2;i++)
  80. for(int j = 0;j <= 2;j++)
  81. { if(dirX[i] != dirY[j]) {
  82. int X = dirX[i]+x;
  83. int Y = dirY[j]+y;
  84. if(ok(X,Y,n,m) && vis[X][Y] == 0)
  85. {
  86. q.add(new Node(X,Y));
  87. vis[X][Y] = vis[x][y]+1;
  88. }}
  89. }
  90.  
  91. }
  92. for(int i = 0;i < n;i++) {
  93. for(int j = 0;j<m;j++)
  94. out.write((vis[i][j]-1)+" ");
  95. out.write("\n");
  96. }
  97.  
  98. }
  99. out.flush();
  100. }
  101. private static boolean ok(int x, int y, int n, int m) {
  102. if(x<0 || y <0 || x>=n || y>=m)
  103. return false;
  104. return true;
  105. }
  106. }
Success #stdin #stdout 0.09s 48284KB
stdin
1
3 4
0001
0011
0110
stdout
3 2 1 0 
2 1 0 0 
1 0 0 1