leetcode 874. Walking Robot Simulation 题解【C++/Java/Python】

Walking Robot Simulation

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.

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:

  1. 0 <= commands.length <= 10000
  2. 0 <= obstacles.length <= 10000
  3. -30000 <= obstacle[i][0] <= 30000
  4. -30000 <= obstacle[i][1] <= 30000
  5. The answer is guaranteed to be less than 2 ^ 31.

题意是一个robot最初往北走,可以接收3种指令:

  • -1是往右转;

  • -2是往左转;

  • 在当前方向上移动1-9个单元。

求robot移动的过程中遇到路障obstacles不能继续往前走,求离原点最大的移动距离的平方。

题目关键是要把3种指令统一起来。假定往北direction = 0,此时向右转,转为向东,direction = 1,再向右转,direction = 2,转为向南,再右转,direction = 3,方向向西。如果再往右转,direction = 0,回到往北的方向。故向右转时,有规律direction = (direction + 1) % 4。 对应地,往左转,有direction = (direction - 1 + 4) % 4。注意,表达式+4是要避免出现-1,此时应该direction = 3

方向问题解决了,再看移动的问题。移动的关键是不能跨过障碍物。可以用set集合把障碍物坐标存下来,一旦遇到障碍物,就停下来,等着接收下一条指令。每接收一次指令,检查一下当前坐标与原点的距离,看能否更新最大值。

class Solution {
public:
    int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
        unordered_set<string> oSet; //存储障碍物坐标
        for(auto o : obstacles) {
            oSet.insert(to_string(o[0]) + "," + to_string(o[1])); //注意不能直接o[0] + "," + o[1],会出错
        }
        int dir = 0, x = 0, y = 0, res = 0;
        vector<vector<int>> dirs = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};// 北、东、南、西
        for(auto c : commands) {
            if(c == -1) {
                dir = (dir + 1) % 4;//向右转,即顺时针转换方向
            }
            else if(c == -2) {//向左转,逆时针转换方向
                dir = (dir - 1 + 4) % 4;
            }
            else {//没遇到障碍物前往前走
                while(c-- > 0 && oSet.find(to_string(x+dirs[dir][0]) + "," + to_string(y+dirs[dir][1])) == oSet.end()) {
                    x += dirs[dir][0];
                    y += dirs[dir][1];
                }
            }
            res = max(res, x * x + y * y);//检查能否更新最大值
        }
        return res;
    }
};

参考资料:
https://leetcode.com/problems/walking-robot-simulation/discuss/152322/Maximum!-This-is-crazy!

猜你喜欢

转载自blog.csdn.net/androidchanhao/article/details/81269418