874. Walking Robot Simulation #475
-
Topics: A robot on an infinite XY-plane starts at point
Some of the grid squares are Return _the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is Note:
Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to simulate the robot's movement on an infinite 2D grid based on a sequence of commands and avoid obstacles if any. The goal is to determine the maximum Euclidean distance squared that the robot reaches from the origin. Approach
Let's implement this solution in PHP: 874. Walking Robot Simulation <?php
/**
* @param Integer[] $commands
* @param Integer[][] $obstacles
* @return Integer
*/
function robotSim($commands, $obstacles) {
// Directions: North, East, South, West
$directions = [[0, 1], [1, 0], [0, -1], [-1, 0]];
$currentDirection = 0; // Start facing North
$x = 0;
$y = 0;
$maxDistanceSquared = 0;
// Convert obstacles array to a set of strings for quick lookup
$obstacleSet = [];
foreach ($obstacles as $obstacle) {
$obstacleSet[$obstacle[0] . ',' . $obstacle[1]] = true;
}
foreach ($commands as $command) {
if ($command == -2) {
// Turn left
$currentDirection = ($currentDirection + 3) % 4;
} elseif ($command == -1) {
// Turn right
$currentDirection = ($currentDirection + 1) % 4;
} else {
// Move forward
for ($i = 0; $i < $command; $i++) {
$nextX = $x + $directions[$currentDirection][0];
$nextY = $y + $directions[$currentDirection][1];
// Check if the next position is an obstacle
if (isset($obstacleSet[$nextX . ',' . $nextY])) {
break; // Stop if hitting an obstacle
}
// Move to the next position
$x = $nextX;
$y = $nextY;
// Calculate the distance squared from the origin
$maxDistanceSquared = max($maxDistanceSquared, $x * $x + $y * $y);
}
}
}
return $maxDistanceSquared;
}
// Test cases
echo robotSim([4,-1,3], []) . "\n"; // Output: 25
echo robotSim([4,-1,4,-2,4], [[2,4]]) . "\n"; // Output: 65
echo robotSim([6,-1,-1,6], []) . "\n"; // Output: 36
?> Explanation:
Test Cases
This solution efficiently handles the problem constraints and calculates the maximum distance squared as required. |
Beta Was this translation helpful? Give feedback.
We need to simulate the robot's movement on an infinite 2D grid based on a sequence of commands and avoid obstacles if any. The goal is to determine the maximum Euclidean distance squared that the robot reaches from the origin.
Approach
Direction Handling:
(0, 1)
(1, 0)
(0, -1)
(-1, 0)
Turning:
(-2)
will shift the direction counterclockwise by 90 degrees.(-1)
will shift the direction clockwise by 90 degrees.Movement: