题目描述:
机器人在一个无限大小的 XY 网格平面上行走,从点 (0, 0) 处开始出发,面向北方。该机器人可以接收以下三种类型的命令 commands :
-2 :向左转 90 度
-1 :向右转 90 度
1 <= x <= 9 :向前移动 x 个单位长度
在网格上有一些格子被视为障碍物 obstacles 。第 i 个障碍物位于网格点 obstacles[i] = (xi, yi) 。
机器人无法走到障碍物上,它将会停留在障碍物的前一个网格方块上,但仍然可以继续尝试进行该路线的其余部分。
返回从原点到机器人所有经过的路径点(坐标为整数)的最大欧式距离的平方。(即,如果距离为 5 ,则返回 25 )注意:
北表示 +Y 方向。
东表示 +X 方向。
南表示 -Y 方向。
西表示 -X 方向。
示例:
解题思路:
将d作为判断方向的依据,实现x轴和y轴的变换,再考虑每一次变换时,障碍物会不会改变移动的距离。
代码附上:
class Solution {
int[][] change=new int[1][1];
int x0=0,y0=0,x=0,y=0,max=0;
public int robotSim(int[] commands, int[][] obstacles) {
// 1为北,2为东,3为南,4为西
int d=1;
for(int i=0;i<commands.length;i++) {
if(commands[i]==-1) {
d++;
if(d==5) d=1;
} else if(commands[i]==-2) {
d--;
if(d==0) d=4;
} else {
motion(d,commands[i]);//x和y的变换
obstacle(obstacles);//障碍
x0+=x;
y0+=y;
}
max=max>(int)Math.pow(x0,2)+(int)Math.pow(y0,2)?max:(int)Math.pow(x0,2)+(int)Math.pow(y0,2);
}
return max;
}
public void motion(int d,int n) {
x=0;y=0;
switch(d) {
case 1:
y=n;
break;
case 2:
x=n;
break;
case 3:
y-=n;
break;
case 4:
x-=n;
break;
}
}
public void obstacle(int[][] obstacles) {
if(x==0) {
if(y>0) {
for(int j=0;j<obstacles.length;j++) {
if(obstacles[j][0]==x0) {
if(obstacles[j][1]>y0&&obstacles[j][1]<=y0+y) {
y=y<obstacles[j][1]-y0?y:obstacles[j][1]-y0-1;
}
}
}
} else {
for(int j=0;j<obstacles.length;j++) {
if(obstacles[j][0]==x0) {
if(obstacles[j][1]<y0&&obstacles[j][1]>=y0+y) {
y=y>obstacles[j][1]-y0?y:obstacles[j][1]-y0+1;
}
}
}
}
}
if(y==0) {
if(x>0) {
for(int j=0;j<obstacles.length;j++) {
if(obstacles[j][1]==y0) {
if(obstacles[j][0]>x0&&obstacles[j][0]<=x0+x) {
x=x<obstacles[j][0]-x0?x:obstacles[j][0]-x0-1;
}
}
}
} else {
for(int j=0;j<obstacles.length;j++) {
if(obstacles[j][1]==y0) {
if(obstacles[j][0]<x0&&obstacles[j][0]>=x0+x) {
x=x>obstacles[j][0]-x0?x:obstacles[j][0]-x0+1;
}
}
}
}
}
}
}