Sponsored
Sponsored
Simulate the movement of the robot by maintaining a variable for the current direction. Use an array to store the possible directions: north, east, south, and west. When a turn command is received, adjust the direction index. For movement commands, move the robot in the direction indexed by the current direction.
Time Complexity: O(N + M), where N is the number of commands and M is the number of obstacles.
Space Complexity: O(M), where M is the number of obstacles.
1#include <vector>
2#include <unordered_set>
3using namespace std;
4
5struct pair_hash {
6 template <class T1, class T2>
7 size_t operator () (const pair<T1, T2>& pair) const {
8 return hash<T1>()(pair.first) ^ hash<T2>()(pair.second);
9 }
10};
11
12int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
13 unordered_set<pair<int,int>, pair_hash> obstacle_set;
14 for (auto& obs : obstacles) {
15 obstacle_set.insert({obs[0], obs[1]});
16 }
17 vector<int> dx = {0, 1, 0, -1};
18 vector<int> dy = {1, 0, -1, 0};
19 int x = 0, y = 0, direction = 0, max_dist_sq = 0;
20
21 for (int cmd : commands) {
22 if (cmd == -2) { // Turn left
23 direction = (direction + 3) % 4;
24 } else if (cmd == -1) { // Turn right
25 direction = (direction + 1) % 4;
26 } else {
27 for (int k = 0; k < cmd; ++k) {
28 int nx = x + dx[direction];
29 int ny = y + dy[direction];
30 if (obstacle_set.find({nx, ny}) == obstacle_set.end()) {
31 x = nx;
32 y = ny;
33 max_dist_sq = max(max_dist_sq, x * x + y * y);
34 } else {
35 break;
36 }
37 }
38 }
39 }
40
41 return max_dist_sq;
42}
This C++ solution uses a similar approach with unordered_set and struct for hashing pairs. The directions are represented with vectors, and position is updated step by step. If an obstacle is encountered, further movement in that command is stopped.