[LeetCode] Walking Robot Simulation

874. Walking Robot Simulation

A robot on an infinite XY-plane starts at point (0, 0) facing north. The robot can receive a sequence of these three possible types of commands:

  • -2: Turn left 90 degrees.
  • -1: Turn right 90 degrees.
  • 1 <= k <= 9: Move forward k units, one unit at a time.

Some of the grid squares are obstacles. The ith obstacle is at grid point obstacles[i] = (xi, yi). If the robot runs into an obstacle, then it will instead stay in its current location and move on to the next command.

Return the maximum Euclidean distance that the robot ever gets from the origin squared (i.e. if the distance is 5, return 25).

Note:

  • North means +Y direction.
  • East means +X direction.
  • South means -Y direction.
  • West means -X direction.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
int dir(0), cx(0), cy(0), res(0), dx[4]{0, 1, 0, -1}, dy[4]{1, 0, -1, 0};
unordered_map<int, unordered_set<int>> o;
for(auto& _o : obstacles) {
o[_o[0]].insert(_o[1]);
}

for(auto& c: commands) {
if(c == -2) dir = (dir + 3) % 4;
else if(c == -1) dir = (dir + 1) % 4;
else {
while(c--) {
int nx = cx + dx[dir];
int ny = cy + dy[dir];
if(o[nx].count(ny)) break;
cx = nx, cy = ny;
}
res = max(res, cx * cx + cy * cy);
}
}

return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/14/PS/LeetCode/walking-robot-simulation/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.