Leetcode:874. 模拟行走机器人

如果机器人试图走到障碍物上方,那么它将停留在障碍物的前一个网格方块上,但仍然可以继续该路线的其余部分。

返回从原点到机器人的最大欧式距离的平方

示例 1:

输入: commands = [4,-1,3], obstacles = []
输出: 25
解释: 机器人将会到达 (3, 4)

示例 2:

输入: commands = [4,-1,4,-2,4], obstacles = [[2,4]]
输出: 65
解释: 机器人在左转走到 (1, 8) 之前将被困在 (1, 4) 处

提示:

  1. 0 <= commands.length <= 10000
  2. 0 <= obstacles.length <= 10000
  3. -30000 <= obstacle[i][0] <= 30000
  4. -30000 <= obstacle[i][1] <= 30000
  5. 答案保证小于 2 ^ 31

解题思路:

坐标的hash,模拟题。判断下一步是否有墙壁,如果没有则走一步,否则停留在原处,等待下一次方向的改变。

题中,墙壁的范围是[-30000,30000]的区间,如何判断一个坐标(x,y)是否是墙,可以将(x,y)转换成long型的整数。

long itoll(int a, int b) {
        return ((a + 30000) << 16) + b + 30000;
    }

注意:一定要将a,b转换成无符号型,即全部相加30000,否则不是严格的一一对应。

C++
static int x = []() {
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    long itoll(int a, int b) {
        return ((a + 30000) << 16) + b + 30000;
    }
    int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
        char direction[4] = { 'U','R','D','L' };
        unordered_set<long> S;
        int dx[4] = { 0,1,0,-1 };
        int dy[4] = { 1,0,-1,0 };
        int pos = 0;
        int x = 0, y = 0;
        int _max = 0;
        int size = commands.size(), i, j;
        for (i = 1; i <= obstacles.size(); i++) {
            S.insert(itoll(obstacles[i - 1][0],obstacles[i - 1][1]));
        }
        for (i = 1; i <= size; i++) {
            if (commands[i - 1] == -2)  pos = (pos + 3) % 4;
            else if (commands[i - 1] == -1) pos = (pos + 1) % 4;
            else {
                for (j = 1; j <= commands[i - 1]; j++) {
                    if (S.count(itoll(x + dx[pos],y + dy[pos])) != 0) {
                        break;
                    }
                    x = x + dx[pos];
                    y = y + dy[pos];
                }
                _max = max(_max , (x*x + y*y));
            }
        }
        return _max;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_23523409/article/details/85996170