fork download
  1. from collections import deque
  2.  
  3. def min_moves_to_destination(M, N, grid, source, dest, move_rule):
  4. # Define directions based on the move rule
  5. dx, dy = move_rule
  6. directions = [
  7. (dx, dy), # forward
  8. (dy, -dx), # right (90° clockwise)
  9. (-dy, dx), # left (90° counterclockwise)
  10. (-dx, -dy) # backward (180°)
  11. ]
  12.  
  13. visited = [[False] * N for _ in range(M)]
  14. sx, sy = source
  15. dx, dy = dest
  16.  
  17. # Early exit if source or destination is blocked
  18. if not (0 <= sx < M and 0 <= sy < N and 0 <= dx < M and 0 <= dy < N):
  19. return -1
  20. if grid[sx][sy] == 1 or grid[dx][dy] == 1:
  21. return -1
  22.  
  23. # BFS queue
  24. queue = deque()
  25. queue.append((sx, sy, 0))
  26. visited[sx][sy] = True
  27.  
  28. while queue:
  29. x, y, steps = queue.popleft()
  30.  
  31. if (x, y) == (dx, dy):
  32. return steps
  33.  
  34. for mx, my in directions:
  35. nx, ny = x + mx, y + my
  36. if 0 <= nx < M and 0 <= ny < N and not visited[nx][ny] and grid[nx][ny] == 0:
  37. visited[nx][ny] = True
  38. queue.append((nx, ny, steps + 1))
  39.  
  40. return -1 # Not reachable
  41.  
  42. # Input reading
  43. def main():
  44. try:
  45. M, N = map(int, input().split())
  46. grid = [list(map(int, input().split())) for _ in range(M)]
  47. source = tuple(map(int, input().split()))
  48. dest = tuple(map(int, input().split()))
  49. move_rule = tuple(map(int, input().split()))
  50.  
  51. result = min_moves_to_destination(M, N, grid, source, dest, move_rule)
  52. print(result)
  53. except Exception as e:
  54. print("Error:", e)
  55.  
  56. if __name__ == "__main__":
  57. main()
  58.  
Success #stdin #stdout 0.1s 14128KB
stdin
6 6
0 1 0 0 0 0
0 0 0 0 0 1
0 1 0 0 0 0
1 1 0 0 0 1
0 0 0 0 0 0
1 1 0 0 1 0
1 0
5 3
1 2
stdout
3