LeetCode 874 题解

874. Walking Robot Simulation

题目大意:二维空间,从原点出发 ,4个方向,走, 路上有障碍,有障碍的地方不能走。

解题思路:模拟

#define mp make_pair

/*
0north 1east 2south 3west
*/
int dx[]={0,1,0,-1};
int dy[]={1,0,-1,0};

class Solution {
public:
    int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
        int n = commands.size();
        int x=0,y=0,f=0;
        map<pair<int,int>,int> p;
        for(int i=0;i<obstacles.size();i++)
        {
            int tx = obstacles[i][0];
            int ty = obstacles[i][1];
            p[mp(tx,ty)] = 1;
        }
        int res = 0;
        for(int i=0;i<n;i++)
        {
            if(commands[i]==-1)
            {
                f = (f+1) %4 ;
            }
            else if(commands[i]==-2)
            {
                f= (f+3) %4 ;
            }
            else
            {
                int d = commands[i];
                while(d)
                {
                    x = x+dx[f];
                    y = y+dy[f];
                    d--;
                    if(p[mp(x,y)]==1)
                    {
                        x = x-dx[f];
                        y = y-dy[f];
                        break;
                    }
                }
                res = max(res, x*x + y*y);
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/u011439455/article/details/81186761
874