分析
-
题目:
-
思路:
- 直接按照题意模拟一遍。
- 我们发现机器人只会绕着网格图的外圈走,因此可以先将多余的圈数去掉,直接取余。
- 140/142测试点过不去,有两类错误:
- 第一种,没有考虑到余数为0的时候,方向可能没有转过来,还是之前的方向。比如饶了一圈回到(0,0),最开始是向右,但是此时正确答案应该向下。
- 第二种,考虑了余数为0,但是直接对方向回退。在有的数据上,并不能直接回退方向,这个方向是固定的,可以写死。

代码
class Robot {
public:
int w, h;
int x, y, d;
string dir[4] = {"East", "North", "West", "South"};
int dx[4]={1, 0, -1, 0};
int dy[4]={0, 1, 0, -1};
Robot(int width, int height) {
w = width;
h = height;
x = 0, y = 0, d = 0;
}
void move(int num) {
// 外一圈的步数,这里不等于周长,而是长宽减一后的周长,最好手动模拟走一下。
// 也可以这样写 int cc = 2*(w-1 + h-1);
int cc = 2*w + 2*h - 4;
num %= cc;
// 140/142没考虑到的测试点 num == 0
if(!num && !x && !y) d = 3;
while(num--) {
int nx = dx[d] + x, ny = dy[d] + y;
if(nx < 0 || nx >= w || ny < 0 || ny >= h) {
// 如果越界了,就逆时针转90度,换到下一个方向继续走
d++, d %= 4;
nx = dx[d] + x, ny = dy[d] + y;
}
x = nx, y = ny;
}
}
vector<int> getPos() {
return {x, y};
}
string getDir() {
return dir[d];
}
};
/**
* Your Robot object will be instantiated and called as such:
* Robot* obj = new Robot(width, height);
* obj->move(num);
* vector<int> param_2 = obj->getPos();
* string param_3 = obj->getDir();
*/