本文主要是介绍java刷题--874模拟行走机器人,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
java刷题--874模拟行走机器人
题目
![在这里插入图片描述](/upload/202107/04/202107041424163305.png)
代码
class Solution {
public int robotSim(int[] commands, int[][] obstacles) {
int[][] directions = new int[][]{{0,1},{1,0},{0,-1},{-1,0}};//建立方向集数组,数组下标0123对应方向北东南西
int direction = 0,x=0,y=0,aer = 0;//方向及位置、最大欧式距离平方
HashSet hashSet = new HashSet();//将阻碍点转为hashSet,方便快速查找
for(int[] obs : obstacles){//把障碍点作为字符串存入hashset
hashSet.add(obs[0]+","+obs[1]);
}
for(int com : commands){//如果com为-1,-2则计算转向后的方向
if(com==-1) direction = (direction+1)%4;//向右转90°
else if(com==-2) direction = (direction+3)%4;//向左转90°==向右转270°
else if(com>0){
while (com -- >0){
int nextX = x+directions[direction][0];//计算下一节点x,y轴位置
int nextY = y+directions[direction][1];
if(!hashSet.contains(nextX+","+nextY)){//判断下一节点,是否为障碍点
x = nextX;
y = nextY;
aer = Math.max(aer,x*x+y*y);
}else break;
}
}
}return aer;
}
}
结果
![在这里插入图片描述](/upload/202107/04/202107041424164920.png)
这篇关于java刷题--874模拟行走机器人的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!