ASMR LeetCode: Walking Robot Simulation | Chill Coding

Поделиться
HTML-код
  • Опубликовано: 3 дек 2024
  • how about implementing the robot to destroy the obstacles :P

Комментарии • 1

  • @LeekCodeDev
    @LeekCodeDev  3 месяца назад +1

    Source Code:
    class Solution:
    def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
    '''
    Solving this problem comes down to being able to simulate
    the process of walking the robot. It seems like we'll need
    some directions array so that we need to switch
    the direction when we encounter a -2 or a -1. We'll also
    make a hash set of the obstacles to make lookup faster...
    Then we simply just go through each commands, stop when
    there's an obstacle, calculate if the distance from
    the origin is greater than our best distance, and update
    accordingly :D
    '''
    directions = [(0,1),(1,0),(0,-1),(-1,0)]
    cur_dir = 0 #North
    cur_pos = [0,0] #origin
    best_dist = 0
    obstaclesSet = set(map(tuple,obstacles))
    for command in commands:
    if command == -2:
    cur_dir = (cur_dir + 3) % 4
    elif command == -1:
    cur_dir = (cur_dir + 1) % 4
    else:
    #going forward
    going = directions[cur_dir]
    for _ in range(command):
    next_pos = [cur_pos[0] + going[0],cur_pos[1] + going[1]]
    if tuple(next_pos) in obstaclesSet:
    break
    cur_pos = next_pos
    if (cur_pos[0]**2 + cur_pos[1]**2 > best_dist):
    best_dist = cur_pos[0]**2 + cur_pos[1] ** 2
    return best_dist