这道题直接按照题意来解,建立坐标系和移动方案,思路是比较简单的。只是需要注意需要使用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[0], obs[1])); } int Wx = 0; int Wy = 1; int Px = 0; int Py = 0; int maxdistance = 0; for (int i = 0; i < N; i++) { int cmd = commands[i];//当前指令 if (cmd == -2)//左转 { if (Wx == 0 && Wy == 1)//上-->左 { Wx = -1; Wy = 0; } else if (Wx == -1 && Wy == 0)//左-->下 { Wx = 0; Wy = -1; } else if (Wx == 0 && Wy == -1)//下-->右 { Wx = 1; Wy = 0; } else if (Wx == 1 && Wy == 0)//右-->上 { Wx = 0; Wy = 1; } } else if (cmd == -1)//右转 { if (Wx == 0 && Wy == 1)//上-->右 { Wx = 1; Wy = 0; } else if (Wx == -1 && Wy == 0)//左-->上 { Wx = 0; Wy = 1; } else if (Wx == 0 && Wy == -1)//下-->左 { Wx = -1; Wy = 0; } else if (Wx == 1 && Wy == 0)//右-->下 { Wx = 0; Wy = -1; } } else//移动 1<=x<=9 { //此次移动之前的起点位置为Px和Py int Tmpx = Px; int Tmpy = Py; while (cmd > 0) { //以(Wx,Wy)为步进,移动一次 Tmpx += Wx; Tmpy += Wy; if (st.find(make_pair(Tmpx, Tmpy)) != st.end()) { Tmpx -= Wx; Tmpy -= Wy; cmd = 0; } cmd--; } int distance = Tmpx*Tmpx + Tmpy*Tmpy; if (maxdistance < distance) { maxdistance = distance; } Px = Tmpx; Py = Tmpy; } } return maxdistance; }