[leetcode]Walking Robot Simulation
链接:https://leetcode.com/problems/walking-robot-simulation/description/
Question
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
: turn left 90 degrees-1
: turn right 90 degrees1 <= x <= 9
: move forwardx
units
Some of the grid squares are obstacles.
The i
-th obstacle is at grid point (obstacles[i][0], obstacles[i][1])
If the robot would try to move onto them, the robot stays on the previous grid square instead (but still continues following the rest of the route.)
Return the square of the maximum Euclidean distance that the robot will be from the origin.
Example 1
Input: commands = [4,-1,3], obstacles = []
Output: 25
Explanation: robot will go to (3, 4)
Example 2
Input: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
Output: 65
Explanation: robot will be stuck at (1, 4) before turning left and going to (1, 8)
Note:
0 <= commands.length <= 10000
0 <= obstacles.length <= 10000
-30000 <= obstacle[i][0] <= 30000
-30000 <= obstacle[i][1] <= 30000
The answer is guaranteed to be less than 2 ^ 31.
Solution
// 啃爹啊!!这道题要返回的是距离原点的最大值,而不是最终值!!
class Solution {
public:
typedef pair<int, int> Pair;
int direction[4][2] = {
{0,1}, // N
{1,0}, // E
{0,-1}, // S
{-1,0} // W
};
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
int dire = 0;
int x = 0, y = 0;
map<pair<int, int>, bool> mp;
int result = 0;
for (int i = 0; i < obstacles.size(); i++) {
int x = obstacles[i][0];
int y = obstacles[i][1];
mp[Pair(x, y)] = true;
}
for (int i = 0; i < commands.size(); i++) {
if (commands[i] == -1) {
dire = (dire+1)%4;
} else if (commands[i] == -2) {
dire = (dire+4-1)%4;
} else {
for (int j = 0; j < commands[i]; j++) {
int new_x = x+direction[dire][0];
int new_y = y+direction[dire][1];
// 有障碍
if (mp.find(Pair(new_x, new_y)) != mp.end()) {
break;
} else {
x = new_x;
y = new_y;
result = max(result, new_x*new_x+new_y*new_y);
}
}
}
}
return result;
}
};
思路:用一个数组direction来表示方向,注意顺序很重要!体现在后面只需将dire+1或者-1就可以表示右转和左转了。也不知道为啥他们说会超时;-)