Untitled

mail@pastecode.io avatar
unknown
plain_text
12 days ago
2.7 kB
5
Indexable
Never
from collections import defaultdict

class Robot:
        def __init__(self, obstacles):
            self.x = 0
            self.y = 0
            self.direction = 'N'
            self.left_dict = {
                'N':'W',
                'W': 'S',
                'S': 'E',
                'E': 'N'
            }
            self.right_dict = {
                'N': 'E',
                'E': 'S',
                'S': 'W',
                'W': 'N'
            }
            self.obstacles_dict = self.load_obstacles(obstacles)
            self.max_euclid = 0

        def turn_left(self):
            self.direction = self.left_dict[self.direction]

        def turn_right(self):
            self.direction = self.right_dict[self.direction]

        def move_forward(self, k: int):
            match self.direction:
                case 'N':
                    for _ in range(k):
                        if self.check_obstacle(self.x, self.y+1):
                            break

                        else:
                            self.y += 1


                case 'E':
                    for _ in range(k):
                        if self.check_obstacle(self.x+1, self.y):
                            break

                        else:
                            self.x += 1

                case 'S':
                    for _ in range(k):
                        if self.check_obstacle(self.x, self.y-1):
                            break

                        else:
                            self.y -= 1

                case 'W':
                    for _ in range(k):
                        if self.check_obstacle(self.x-1, self.y):
                            break

                        else:
                            self.x -= 1

            self.set_euclidean_max()

        def load_obstacles(self, obstacles):
            obstacle_dict = defaultdict(set)
            
            for x, y in obstacles:
                obstacle_dict[x].add(y)

            return obstacle_dict

        def check_obstacle(self, x, y):
            return x in self.obstacles_dict and y in self.obstacles_dict[x]

        def set_euclidean_max(self):
            self.max_euclid = max(self.max_euclid, pow(self.x, 2) + pow(self.y, 2))

class Solution:
    def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
        robot = Robot(obstacles)

        for command in commands:
            match command:
                case -2:
                    robot.turn_left()

                case -1:
                    robot.turn_right()

                case _:
                    robot.move_forward(command)

        return robot.max_euclid
Leave a Comment