gpt4 book ai didi

c++ - 这一步背后的直觉?

转载 作者:搜寻专家 更新时间:2023-10-31 00:52:31 26 4
gpt4 key购买 nike

我正在尝试解决 a question来自今天早些时候举行的 LeetCode 竞赛:

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 degrees
1 <= x <= 9: move forward x 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.

公认的解决方案如下:

typedef pair<int, int> ii;
const int d[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
class Solution {
public:
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
set<ii> A;
for (auto& it : obstacles) {
A.insert({it[0], it[1]});
}
int dir = 0, x = 0, y = 0;
int ret = 0;
for (auto& it : commands) {
if (it == -2) {
dir = (dir + 3) % 4;
} else if (it == -1) {
dir = (dir + 1) % 4;
} else {
for (int k = 0; k < it; ++k) {
int nx = x + d[dir][0];
int ny = y + d[dir][1];
if (A.count({nx, ny})) break;
x = nx;
y = ny;
}
}
ret = max(ret, x * x + y * y);
}
return ret;
}
};

我的问题是,在计算 dir 时,在下面的公式中添加 31 背后的直觉是什么:

dir=(dir+3)%4;
^?
dir=(dir+1)%4;
^?

谢谢!

编辑:如果it==-2则表示机器人向左移动;而如果 it==-1 则意味着它向右移动。添加 31 如何确保改变方向

最佳答案

方向定义为:

      0        |   3 ------- 1      |        2  

开始时您面向北方 (dir = 0)

如果你想向右走(即 -90 度),那么你需要面向“1”,即 0+1 (dir+1)
如果你想向左走(即+90度)那么你需要面对“3”,这是 0+3 (dir+3)

就是这样!希望我足够清楚,祝你好运;)

关于c++ - 这一步背后的直觉?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51462291/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com