Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Mô phỏng robot đi bộ (Walking Robot Simulation) trong Python


Giả sử robot trên lưới vô hạn bắt đầu tại (0,0), hướng về bắc. Robot nhận 3 loại lệnh:

  1. -2: quay trái 90 độ
  2. -1: quay phải 90 độ
  3. 1-9: tiến x đơn vị
  4. Có chướng ngại vật tại các ô grid.
  5. Mảng obstacles cho chướng ngại vật i tại (obstacles[i][0], obstacles[i][1]). Nếu robot muốn di chuyển vào ô chướng ngại, nó ở lại ô trước.

    Tìm bình phương khoảng cách Euclid tối đa từ gốc.

    Ví dụ, commands=[4,-1,4,-2,4], obstacles=[[2,4]], đầu ra 65, robot kẹt tại (1,4) trước khi quay trái đi (1,8).

    Giải quyết:

    • position_offset := [(0,1),(1,0),(0,-1),(-1,0)]
    • Khởi tạo x,y,direction,max_distance = 0
    • for command in commands:
      • if command == -2: direction = (direction-1)%4
      • elif command == -1: direction = (direction+1)%4
      • else: (x_off,y_off) = position_offset[direction]
      • while command != 0:
        • if (x+x_off, y+y_off) không trong obstacles: x+=x_off, y+=y_off
        • command -= 1
      • max_distance = max(max_distance, x^2 + y^2)
    • return max_distance

    Xem triển khai:

    Ví dụ

    class Solution:
        def robotSim(self, commands, obstacles):
            position_offset = [(0, 1), (1, 0), (0, -1), (-1, 0)]
            obstacles = set(map(tuple, obstacles))
            x, y, direction, max_distance = 0, 0, 0, 0
            for command in commands:
                if command == -2:
                    direction = (direction - 1) % 4
                elif command == -1:
                    direction = (direction + 1) % 4
                else:
                    x_off, y_off = position_offset[direction]
                    while command:
                        if (x + x_off, y + y_off) not in obstacles:
                            x += x_off
                            y += y_off
                        command -= 1
                    max_distance = max(max_distance, x**2 + y**2)
            return max_distance
    ob = Solution()
    print(ob.robotSim([4,-1,4,-2,4], [[2,4]]))

    Đầu vào

    [4,-1,4,-2,4],[[2,4]]

    Đầu ra

    65