Skip to content

Commit 7beac22

Browse files
authored
Added 874
1 parent 27477a2 commit 7beac22

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

874-walking-robot/solution.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
from typing import List, Set, Tuple
2+
3+
class Solution:
4+
def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
5+
# Directions in the order of North, East, South, West
6+
direction_vectors = [(0, 1), (1, 0), (0, -1), (-1, 0)]
7+
8+
# Initial position and direction (0 -> North, 1 -> East, 2 -> South, 3 -> West)
9+
x, y = 0, 0
10+
direction = 0
11+
12+
# Convert obstacles to a set of tuples for O(1) lookup
13+
obstacle_set: Set[Tuple[int, int]] = set(map(tuple, obstacles))
14+
15+
# Variable to store the maximum distance squared
16+
max_distance_squared = 0
17+
18+
for command in commands:
19+
if command == -2:
20+
# Turn left (counterclockwise)
21+
direction = (direction - 1) % 4
22+
elif command == -1:
23+
# Turn right (clockwise)
24+
direction = (direction + 1) % 4
25+
else:
26+
# Move forward command units
27+
for _ in range(command):
28+
# Calculate the next position
29+
next_x = x + direction_vectors[direction][0]
30+
next_y = y + direction_vectors[direction][1]
31+
32+
# Check if the next position is an obstacle
33+
if (next_x, next_y) not in obstacle_set:
34+
# Update the position
35+
x, y = next_x, next_y
36+
# Update the maximum distance squared
37+
max_distance_squared = max(max_distance_squared, x * x + y * y)
38+
else:
39+
# Stop moving if an obstacle is encountered
40+
break
41+
42+
return max_distance_squared

0 commit comments

Comments
 (0)