1,题目要求
A robot on an infinite grid starts at point (0, 0) and faces north. The robot can receive one of three possible types of commands:
对于一个机器人,给出它的行驶方向和距离,计算它距离起点的最大距离。
2,题目思路
对于这道题,需要注意的是这个距离是最大的距离,而不是机器人到达终点之后到起点的距离,因此需要每执行一步就计算一次距离的最大值。
另外,还值得注意的是,pair不能作为unorder_set的参数。
3,程序源码
static int pr = []() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
set<pair<int, int>> obs;
vector<vector<int>> dir {{0, 1}, {-1, 0}, {0, -1}, {1, 0}};
int d = 0, res = 0, x = 0, y = 0;
for(auto o : obstacles)
obs.insert(make_pair(o[0], o[1]));
for(auto c :commands)
{
if(c == -2)
d = (d + 1) % 4;
else if(c == -1)
d = (d - 1 + 4) % 4;
else
while(c-- && obs.find(make_pair(x+dir[d][0], y+dir[d][1])) == obs.end())
{
x +=dir[d][0];
y +=dir[d][1];
}
res = max(res, x*x+y*y);
}
return res;
}
};