Notes:
This question is pretty straightforward, as labeled as easy.
The first step, we can put all the obstacles into a set. In this way, we can easily to tell whether it is a obstacle or not.
The second, we need a variable to represents the direction. There are four directions: north, east, south, and west, which can be labeled by 0, 1, 2, and 3, respectively.
Then turn left can be updated by (d + 3) % 4, and turn right can be updated as (d + 1)%4.
When d = 0, the x is updated by + 0, and y is updated by + 1;
when d = 1, x + 1, + 0;
when d = 2, x + 0, - 1;
when d = 3, x - 1, + 0;
Thus, we can simply these by using a one-dimensional direction array.
See the code below:
class Solution {
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
int res = 0;
set<vector<int>> ob;
for(auto &a : obstacles) ob.insert(a);
int x = 0, y = 0, d = 0;
vector<int> dirs={0, 1, 0, -1, 0};
for(auto &a : commands) {
if(a == -2) d = (d + 3)%4;
else if(a == -1) d = (d + 1)%4;
else {
for(int i=0; i<a; ++i) {
if(ob.count({x + dirs[d], y + dirs[d+1]})) break;
else {
x += dirs[d];
y += dirs[d+1];
}
res = max(res, x*x + y*y);
}
}
}
return res;
}
};
No comments:
Post a Comment