leetcode 874. Walking Robot Simulation
程序员文章站
2024-03-19 08:55:22
...
一道很基础的题。被卡在的点就是如何判断是否被阻拦住,这里采用一步一步的走,然后用set来存储所有的障碍点,这样每走一步就判断一下。
class Solution {
public int robotSim(int[] commands, int[][] obstacles) {
int[][] derections = new int[][]{{0,1},{-1,0},{0,-1},{1,0}};
int derect = 0;
int resx=0,resy=0;
int max = 0;
HashSet<String> set = new HashSet<>();
for(int[] num : obstacles){
set.add(String.valueOf(num[0])+"-"+String.valueOf(num[1]));
}
for(int i=0;i<commands.length;i++){
if(commands[i]==-2){
derect = (derect+1)%4;
}else if(commands[i]==-1){
derect = (derect+3)%4;
}else{
while(commands[i]>0&&!set.contains(String.valueOf(resx+derections[derect][0])+"-"+String.valueOf(resy+derections[derect][1]))){
resx += derections[derect][0];
resy += derections[derect][1];
commands[i]-=1;
max = Math.max(max,resx*resx+resy*resy);
}
}
}
return max;
}
}
看了一下十个月前用python写的代码,简洁简单。
class Solution:
def robotSim(self, commands: List[int], obstacles: List[List[int]]) -> int:
obstacle = set([tuple(pos) for pos in obstacles])
loc = [0,0]
d = [0,1]
max_distance = 0
for i in commands:
if i == -1:
d[0],d[1]=d[1],-d[0]
elif i == -2:
d[0],d[1]=-d[1],d[0]
elif 1<=i<=9:
step = i
while step>0:
if (loc[0]+d[0],loc[1]+d[1]) in obstacle:
break
loc[0] += d[0]
loc[1] += d[1]
step -= 1
max_distance = max(max_distance,loc[0]**2+loc[1]**2)
return max_distance