题目描述
机器人在一个无限大小的网格上行走,从点 (0, 0) 处开始出发,面向北方。该机器人可以接收以下三种类型的命令:
-2
:向左转 90 度-1
:向右转 90 度1 <= x <= 9
:向前移动x
个单位长度
在网格上有一些格子被视为障碍物。
第 i
个障碍物位于网格点 (obstacles[i][0], obstacles[i][1])
如果机器人试图走到障碍物上方,那么它将停留在障碍物的前一个网格方块上,但仍然可以继续该路线的其余部分。
返回从原点到机器人的最大欧式距离的平方。
示例 1:
输入: commands = [4,-1,3], obstacles = [] 输出: 25 解释: 机器人将会到达 (3, 4)
示例 2:
输入: commands = [4,-1,4,-2,4], obstacles = [[2,4]] 输出: 65 解释: 机器人在左转走到 (1, 8) 之前将被困在 (1, 4) 处
提示:
0 <= commands.length <= 10000
0 <= obstacles.length <= 10000
-30000 <= obstacle[i][0] <= 30000
-30000 <= obstacle[i][1] <= 30000
- 答案保证小于
2 ^ 31
解题思路
个人感觉本题翻译有些问题,会给人造成的错觉是最大的距离是在所有可能停止的位置或最终位置,但是按上述思想编写的代码只能通过27个测试用例,将代码改成机器人行走过程中所有位置的最大距离就能ac掉了(陷于手残水平,写的代码过于丑陋不够优雅,尽请谅解)
struct point{
int x;
int y;
point(){}
point(int _x,int _y):x(_x),y(_y){}
};
class Solution {
public:
point cur = point(0,1);
int dir(){
if(cur.x == 0 && cur.y == 1)return 0;
else if(cur.x == -1 && cur.y == 0)return 1;
else if(cur.x == 0 && cur.y == -1)return 2;
else return 3;
}
void changeDir(int cmd){
int tmp = dir();
if(cmd == -2){
switch(tmp){
case 0:{
cur.x = -1;cur.y=0;
}break;
case 1:{
cur.x = 0;cur.y = -1;
}break;
case 2:{
cur.x = 1;cur.y=0;
}break;
case 3:{
cur.x = 0;cur.y = 1;
}break;
}
}else{
switch(tmp){
case 0:{
cur.x = 1;cur.y=0;
}break;
case 1:{
cur.x = 0;cur.y = 1;
}break;
case 2:{
cur.x = -1;cur.y=0;
}break;
case 3:{
cur.x = 0;cur.y = -1;
}break;
}
}
}
int robotSim(vector<int>& commands, vector<vector<int>>& obstacles) {
set<int> obs;
int maxdis = 0,len = obstacles.size();
for(int i=0;i<len;i++) obs.insert(30000*obstacles[i][0]+obstacles[i][1]);
point cur_pos = point(0,0);
len = commands.size();
for(int i=0;i<len;i++){
int cmd = commands[i];
if(cmd >= 1){
int tmp = dir();
switch(tmp){
case 0:{
while(cmd){
cur_pos.y++;
if(obs.find(cur_pos.x*30000+cur_pos.y) != obs.end()){
cur_pos.y--;
maxdis = max(maxdis,cur_pos.x*cur_pos.x+cur_pos.y*cur_pos.y);
break;
}
maxdis = max(maxdis,cur_pos.x*cur_pos.x+cur_pos.y*cur_pos.y);
cmd--;
}
}break;
case 1:{
while(cmd){
cur_pos.x--;
if(obs.find(cur_pos.x*30000+cur_pos.y) != obs.end()){
cur_pos.x++;
maxdis = max(maxdis,cur_pos.x*cur_pos.x+cur_pos.y*cur_pos.y);
break;
}
maxdis = max(maxdis,cur_pos.x*cur_pos.x+cur_pos.y*cur_pos.y);
cmd--;
}
}break;
case 2:{
while(cmd){
cur_pos.y--;
if(obs.find(cur_pos.x*30000+cur_pos.y) != obs.end()){
cur_pos.y++;
maxdis = max(maxdis,cur_pos.x*cur_pos.x+cur_pos.y*cur_pos.y);
break;
}
maxdis = max(maxdis,cur_pos.x*cur_pos.x+cur_pos.y*cur_pos.y);
cmd--;
}
}break;
case 3:{
while(cmd){
cur_pos.x++;
if(obs.find(cur_pos.x*30000+cur_pos.y) != obs.end()){
cur_pos.x--;
maxdis = max(maxdis,cur_pos.x*cur_pos.x+cur_pos.y*cur_pos.y);
break;
}
maxdis = max(maxdis,cur_pos.x*cur_pos.x+cur_pos.y*cur_pos.y);
cmd--;
}
}break;
}
}else changeDir(cmd);
}
maxdis = max(maxdis,cur_pos.x*cur_pos.x+cur_pos.y*cur_pos.y);
return maxdis;
}
};