Advertisement
hoanmalai

King's Path

Oct 6th, 2021
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. limit = 10^9
  2. mark = set
  3. dist = map
  4. dx = [0, 0, 1, -1, 1, -1, 1, -1]
  5. dy = [1, -1, 0, 0, 1, -1, -1, 1]
  6.  
  7. def calc(x, y):
  8. return x * limit + y
  9.  
  10. def bfs():
  11. q = queue
  12. s = calc(x0, y0)
  13. q.add(s)
  14. dist[s] = 0
  15.  
  16. while q not empty:
  17. u = q.front
  18. q.pop
  19. x = u div limit
  20. y = u mod limit
  21.  
  22. for i = 0 to 7:
  23. newX = x + dx[i]
  24. newY = y + dy[i]
  25. v = calc(newX, newY)
  26. if (0 <= newX < limit and 0 <= newY < limit and v in mark):
  27. if v not in dist:
  28. dist[v] = dist[u] + 1
  29. if v == calc(x1, y1):
  30. return dist[v]
  31. q.add(v)
  32. return -1
  33.  
  34. read(x0, y0, x1, y1)
  35. x0 -= 1, y0 -= 1, x1 -= 1, y1 -= 1
  36. mark.add(calc(x0, y0))
  37. mark.add(calc(x1, y1))
  38.  
  39. read(n)
  40.  
  41. for i = 1 to n:
  42. read(r, a, b)
  43. r -= 1, a -= 1, b -= 1
  44. for j = a to b:
  45. mark.add(calc(r, j))
  46.  
  47. print(bfs())
  48.  
  49. ĐPT: O(V * logV)
  50. V là số lượng ô đi được
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement