欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode - 874. Walking Robot Simulation

程序员文章站 2024-03-19 08:37:58
...

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)

思路:

    我的思路比较直接,先把障碍存在一个set里,方便以后查找判断。然后循环遍历commands,把所有指令执行完,每次计算目前最大的x^2 + y^2,用一个大小为2的数组来表示X、Y坐标,之后只需要用axis=0来表示X,axis=1来表示Y即可,不需要知道到底是哪个轴。在进行移动的时候,每次只走一格,计算max_square。值得注意的是,max_square的初始值为0,因为如果被障碍遮挡或者根本没有移动指令导致原地不动的情况下,最大值是0(最开始我设的初始值为-1,就错了)。

    AC代码如下:

int robotSim(vector<int>& commands, vector<vector<int>>& obstacles)
{
    set<pair<int, int>> obs;
    for(int i = 0; i < obstacles.size(); i++)
        obs.insert(make_pair(obstacles[i][0], obstacles[i][1]));

    int coord[2] = {0, 0};
    int dir = 1;    // 0: x, 1: y, 2: -x, 3: -y
    int max_square = 0;
    for(int i = 0, len = commands.size(); i < len; i++)
    {
        if(commands[i] == -2)
            dir = (dir + 1) % 4;
        else if(commands[i] == -1)
            dir = (dir + 3) % 4;    // (dir - 1) % 4 会出现负数
        else
        {
            int forward = 1;
            int axis = -1;
            switch(dir)
            {
                case 0:
                    axis = 0;  forward = 1;
                    break;
                case 1:
                    axis = 1;  forward = 1;
                    break;
                case 2:
                    axis = 0;  forward = -1;
                    break;
                case 3:
                    axis = 1;  forward = -1;
                    break;
                default:
                    break;
            }
                
            for(int m = 0; m < commands[i]; m++)
            {
                coord[axis] += forward;
                if(obs.find(make_pair(coord[0], coord[1])) != obs.end())
                {
                    coord[axis] -= forward;
                    break;
                }
                int tmp = coord[0] * coord[0] + coord[1] * coord[1];
                max_square = max(max_square, tmp);
            }
        }
    }
    return max_square;
}

 

相关标签: LeetCode