算法小知识----11.17----模仿机器人行走II

229 阅读2分钟

这是我参与11月更文挑战的第17天,活动详情查看:2021最后一次更文挑战

模仿机器人行走II

这是力扣的5911题——模仿机器人行走II(中等题),该题为我参加2021.11.13的双周赛时题型

审题

请你实现 Robot 类:

Robot(int width, int height) 初始化一个 width x height 的网格图,机器人初始在 (0, 0) ,方向朝 "East" 。 void move(int num) 给机器人下达前进 num 步的指令。 int[] getPos() 返回机器人当前所处的格子位置,用一个长度为 2 的数组 [x, y] 表示。 String getDir() 返回当前机器人的朝向,为 "North" ,"East" ,"South" 或者 "West" 。

  • 简单来说就是,给一个二维矩阵,实现类里面的三个方法

    • move:移动
    • getPos:返回当前坐标
    • getDir:返回当前方向
  • 思路其实很多,但是不能被题目内的描述所迷惑,找出其中的关键线索

    • 二维矩阵,且需注意,无论怎么move,都只会在外围行走
    • 计算步数 ≠ 暴力循环;可以利用除余的方式,来获得真正需要走的步数
    • 主要的重点可以放在move方法,定义两个变量去实现方向和坐标即可
  • 踩雷:方法很多,但这是在不考虑超时和空间的前提下

    • (×)暴力循环:直接循环num步数,对于整个圈

    • (×)递归:其实本质上和暴力差不多,但是代码量少了很多;

      • 严重踩坑!!测试用例的数据会巨大,一般来说递归遇上邪魔测试用例都会栈溢出 (周赛就是因为测试用例太大导致压栈太深而超时)
    • (√)num取余:记录走的总步数并取余,每次都是只对一圈进行处理

编码

总的来说,这题还是挺常见的设计题;冷静下来还是不难做出来的

class Robot {
    private int[][] array;
    private int x;
    private int max;
    private int width;
    private int height;
    private int round;
    private int y;
    // 0 是右,1是上,2是左,3是下
    private int pos;
​
    public Robot(int width, int height) {
        array = new int[width][height];
        this.width = width;
        this.height = height;
        this.round = 2*(width+height) - 4;
        x = 0;
        max = 0;
        y = 0;
        pos = 0;
    }
​
    public void move(int num) {
        if (num == 0){
            return;
        }
        max +=num;
        int squrt = max % round;
        if (squrt >=1 && squrt<=width-1){
            pos = 0;
            x = squrt;
            y = 0;
        }else if (squrt>width-1 && squrt<=(width+height) - 2){
            pos = 1;
            y = squrt - (width - 1);
            x = width - 1;
​
        }else if (squrt >(width+height)-2 && squrt<=(2*width+height-3 )){
            pos = 2;
            x = (2*width+height-3 ) - squrt;
            y = height -1;
        }else if (squrt >(2*width+height-3) && squrt<= 2*(width+height) - 4){
            pos = 3;
            y = 2*(width+height) - 4 - squrt;
            x = 0;
        }else {
            pos = 3;
            x = 0;y = 0;
        }
    }
​
    public int[] getPos() {
        return new int[]{x,y};
    }
​
    public String getDir() {
        switch (pos){
            case 0:return "East";
            case 1:return "North";
            case 2:return "West";
            case 3:return "South";
            default:return "East";
        }
    }
}

1636948427(1).jpg