2023-07-19力扣每日一题

链接:

874. 模拟行走机器人

题意:

模拟机器人操作,求操作过程中机器人离原点的最大欧式距离

解:

模拟,难点在于如何判断这个位置是否有障碍,障碍的坐标在正负3E4内,没办法用正常的数组(也许bitset)?

可以用map和set存储顺便去重,然后count查询该位置是否障碍即可

实际代码:

#include
using namespace std;
constexpr int Nmax=1E5+7;
int robotSim(vector& commands, vector>& obstacles)
{
    int move[4][2]={ {0,1},{1,0},{0,-1},{-1,0}};//从左到右 符合右转
    map,int>obsmap;
    for(auto obstacle:obstacles)
    {
        pairtemp{obstacle[0],obstacle[1]};
        obsmap[temp]=1;
    }
    int ans=0,movemode=0,nowx=0,nowy=0;
    for(auto command:commands)
    {
        if(command==-2)
        {
            if(--movemode==-1) movemode=3;
            continue;
        }
        if(command==-1)
        {
            if(++movemode==4) movemode=0;
            continue;
        }
        
        for(int i=1;i<=command;i++)
        {
            int nextx=nowx+move[movemode][0],nexty=nowy+move[movemode][1];
            pairtemp{nextx,nexty};
            if(obsmap.count(temp)==0)
            {
                nowx=nextx;nowy=nexty;
            }
            else break;
        }
        //cout< commands;
    vector> obstacles;
    int a,b,n;cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>a;
        commands.push_back(a);
    }
    while(cin>>a>>b)
    {
        vectortemp{a,b};
        obstacles.push_back(temp);
    }
    int ans=robotSim(commands,obstacles);
    cout<

限制:

  • 1 <= commands.length <= 104
  • commands[i] is one of the values in the list [-2,-1,1,2,3,4,5,6,7,8,9].
  • 0 <= obstacles.length <= 104
  • -3 * 104 <= xi, yi <= 3 * 104
  • 答案保证小于 231

你可能感兴趣的:(力扣每日一题,leetcode)