Advertisement
serega1112

Tablet

Mar 14th, 2021
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.66 KB | None | 0 0
  1.  
  2. n, m = map(int, input().split())
  3.  
  4. matrix = []
  5. while n:
  6.     matrix.append(list(map(int, input().split())))
  7.     n -= 1
  8.  
  9. res = []
  10. q = []
  11.  
  12. for i in range(len(matrix)):
  13.     row = []
  14.     for j in range(m):
  15.         if matrix[i][j] == 1:
  16.             row.append(0)
  17.             q.append((i, j))
  18.         else:
  19.             row.append(-1)
  20.     res.append(row)
  21.  
  22. while q:
  23.     x, y = q.pop(0)
  24.     for xp, yp in [(x+1, y), (x-1, y), (x, y+1), (x, y-1)]:
  25.         if 0 <= xp < len(matrix) and 0 <= yp < m and res[xp][yp] == -1:
  26.             q.append((xp, yp))
  27.             res[xp][yp] = res[x][y] + 1
  28.  
  29. for row in res:
  30.     print(' '.join([str(elem) for elem in row]))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement