这道题直接按照题意来解,建立坐标系和移动方案,思路是比较简单的。只是需要注意需要使用set来判断是否遇到障碍,否则会超时。

int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {

    int N = commands.size();
int M = obstacles.size(); //向上 Wx=0,Wy=1
//向左 Wx=-1,Wy=0
//向下 Wx=0,Wy=-1
//向右 Wx=1,Wy=0 set<pair<int, int>> st;
for (auto &obs : obstacles)
{
st.insert(make_pair(obs[], obs[]));
} int Wx = ;
int Wy = ; int Px = ;
int Py = ;
int maxdistance = ; for (int i = ; i < N; i++)
{
int cmd = commands[i];//当前指令
if (cmd == -)//左转
{
if (Wx == && Wy == )//上-->左
{
Wx = -;
Wy = ;
}
else if (Wx == - && Wy == )//左-->下
{
Wx = ;
Wy = -;
}
else if (Wx == && Wy == -)//下-->右
{
Wx = ;
Wy = ;
}
else if (Wx == && Wy == )//右-->上
{
Wx = ;
Wy = ;
}
}
else if (cmd == -)//右转
{
if (Wx == && Wy == )//上-->右
{
Wx = ;
Wy = ;
}
else if (Wx == - && Wy == )//左-->上
{
Wx = ;
Wy = ;
}
else if (Wx == && Wy == -)//下-->左
{
Wx = -;
Wy = ;
}
else if (Wx == && Wy == )//右-->下
{
Wx = ;
Wy = -;
}
}
else//移动 1<=x<=9
{
//此次移动之前的起点位置为Px和Py
int Tmpx = Px;
int Tmpy = Py;
while (cmd > )
{
//以(Wx,Wy)为步进,移动一次
Tmpx += Wx;
Tmpy += Wy; if (st.find(make_pair(Tmpx, Tmpy)) != st.end())
{
Tmpx -= Wx;
Tmpy -= Wy;
cmd = ;
}
cmd--;
}
int distance = Tmpx*Tmpx + Tmpy*Tmpy;
if (maxdistance < distance)
{
maxdistance = distance;
}
Px = Tmpx;
Py = Tmpy;
}
} return maxdistance;
}
05-27 23:50