LeetCode874 模拟行走机器人(简单模拟—Java之HashSet简单应用)

题目:

机器人在一个无限大小的网格上行走,从点 (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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/walking-robot-simulation

思路:

这里的题目是行走过程中出现的最大值,而不是终点的距离平方。

用dir[][]数组表示好四个方向之后(第一维下标从0开始),用对4取余的方式来控制左转和右转,左转是+3,右转是+1。

在更新位置之前,应该先判断更新后的位置上是不是有障碍,没有障碍在更新。剩下的就是模拟了。

代码:

import java.util.*;
import java.math.*;


class Solution {
    public int robotSim(int[] commands, int[][] obstacles) {
        int[][] dir = {{0,1},{1,0},{0,-1},{-1,0}};
        int mod_dir = 0;//初始方向
        int ans = 0;    //最终结果
        Set<String> dir_set = new HashSet<>();
        for (int i=0; i<obstacles.length; i++) {
            dir_set.add(obstacles[i][0]+","+obstacles[i][1]);
        }
        int posx = 0,posy = 0;
        for(int c : commands){
            if(c == -1){
                mod_dir = (mod_dir+1) % 4;
            }else if(c == -2){
                mod_dir = (mod_dir+3) % 4;
            }else if(c > 0){
                for(int i=0; i<c; i++){
                    if(dir_set.contains((posx + dir[mod_dir][0]) + "," + (posy + dir[mod_dir][1]))){
                        //System.out.println(posx+","+posy+"is exit!!");
                        break;
                    }
                    posx = posx + dir[mod_dir][0];
                    posy = posy + dir[mod_dir][1];
                    ans = Math.max(ans, posx*posx+posy*posy);
                }
            }
        }
        return ans;
    }
}
public class Main {
    public static void main(String[] args){
        Scanner scanner = new Scanner(System.in);
        Solution solution = new Solution();
        int n = scanner.nextInt();
        int m = scanner.nextInt();
        int[] command = new int[n];
        int[][] ob = new int[m][2];
        for(int i=0; i<n; i++){
            command[i] = scanner.nextInt();
        }
        for(int i=0; i<m; i++){
            ob[i][0] = scanner.nextInt();
            ob[i][1] = scanner.nextInt();
        }
        System.out.println(solution.robotSim(command, ob));
    }
}
/*
5
1
4 -1 4 -2 4
2 4
*/
原文地址:https://www.cnblogs.com/sykline/p/12249464.html