Leetcode 874. Walking Robot Simulation
You are given an array of integers commands
representing the commands to control a robot. The robot starts at the origin (0, 0) and faces the positive Y-axis. Each integer in the commands
array has the following meanings:
-2
: turn left 90 degrees-1
: turn right 90 degrees1 <= x <= 9
: move forward x
unitsAdditionally, you are given an array obstacles
where obstacles[i] = [x_i, y_i]
represents a barrier at coordinates (x_i, y_i)
.
The robot should simulate the movement given the commands while avoiding obstacles. The goal is to determine the maximum Euclidean distance from the origin (0, 0)
to any point the robot reaches.
commands
and obstacles
?
(0, 0)
.(0, 1)
(1, 0)
(0, -1)
(-1, 0)
-2
and -1
).1
to 9
).#include <vector>
#include <unordered_set>
#include <unordered_map>
#include <algorithm>
using namespace std;
class Solution {
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
// Direction vectors for north, east, south, west
vector<pair<int, int>> directions = \{\{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
// Use a set to store the obstacle positions
unordered_set<string> obstacleSet;
for (auto& obs : obstacles) {
obstacleSet.insert(to_string(obs[0]) + "," + to_string(obs[1]));
}
// Start at origin, facing north
int x = 0, y = 0, d = 0; // direction index (north)
int maxDist = 0;
for (int command : commands) {
if (command == -2) {
// Turn left
d = (d + 3) % 4;
} else if (command == -1) {
// Turn right
d = (d + 1) % 4;
} else {
// Move forward
for (int i = 0; i < command; ++i) {
int nx = x + directions[d].first;
int ny = y + directions[d].second;
if (obstacleSet.find(to_string(nx) + "," + to_string(ny)) == obstacleSet.end()) {
x = nx;
y = ny;
maxDist = max(maxDist, x * x + y * y);
} else {
break; // obstacle found, stop moving in this direction
}
}
}
}
return maxDist;
}
};
k
is the number of obstacles.This ensures that even for larger inputs, the solution remains efficient.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?