Advertisement
Guest User

Untitled

a guest
Apr 24th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. from typing import *
  2.  
  3.  
  4. class Solution:
  5.  
  6. def updateMatrix(self, matrix: List[List[int]]) -> List[List[int]]:
  7. if not matrix:
  8. return []
  9. distance = []
  10. for i in range(len(matrix)):
  11. temp_distances = []
  12. for j in range(len(matrix[0])):
  13. temp_distances.append(65535)
  14. distance.append(temp_distances)
  15. for i in range(len(matrix)):
  16. for j in range(len(matrix[0])):
  17. if matrix[i][j] == 0:
  18. distance[i][j] = 0
  19. continue
  20. self.get_distance(matrix, i, j, distance)
  21. for i in range(len(matrix) - 1, -1, -1):
  22. for j in range(len(matrix[0]) - 1, -1, -1):
  23. if matrix[i][j] == 0:
  24. distance[i][j] = 0
  25. continue
  26. self.get_distance(matrix, i, j, distance, 1)
  27. return distance
  28.  
  29. def get_distance(self, matrix: List[List[int]], x: int, y: int, distance: List[List[int]], left_or_right=0):
  30. position = []
  31. direction = [(-1, 0), (0, -1)] if left_or_right == 0 else [(-1, 0), (0, -1), (1, 0), (0, 1)]
  32. for d_x, d_y in direction:
  33. f_x, f_y = x + d_x, y + d_y
  34. if f_x < 0 or f_x >= len(matrix) or f_y < 0 or f_y >= len(matrix[0]):
  35. continue
  36. position.append((f_x, f_y))
  37. if position:
  38. distance[x][y] = min([distance[t_x][t_y] for t_x, t_y in position]) + 1
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement