美文网首页
刷题(14)489. Robot Room Cleaner

刷题(14)489. Robot Room Cleaner

作者: MuMuMiu | 来源:发表于2022-01-22 08:42 被阅读0次

昨天刷到一个很有意思的题目,489. Robot Room Cleaner, 是hard题,我顺便看了下半年内的公司选这道题目面试的tag, google facebook这种大厂非常多次。 

这道题做完就会想会不会家里的扫地机器人也是这个算法?你猜你家里的扫地机器人用的是什么算法呢?哈哈肯定不是这个。

这个题目乍一看感觉有点难,因为机器人是randomly安排起始点的,但是题目很清楚地表示了用一个m*n的方格子来作为maze,这个就相当于给了很多限制。然后后面还有机器人到达一个方块的时候,如何知道是面朝什么方向的呢?

这道题的leetcode solution给我们指向了一个maze algorithm的wiki,solution用的就是right-hand rule。这个就让思路很清晰了。另外solution比较tricky的就是仍然用一个矩阵来记录visited node 来帮助backtrack。以起始点为原坐标,构建矩阵。

solution:

class Solution {

    int[][] directions = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    Set<Pair<Integer, Integer>> visited = new HashSet<>();

    Robot robot;

    private void goback() {

        robot.turnRight();

        robot.turnRight();

        robot.move();

        robot.turnRight();

        robot.turnRight();

    }

    private void backtrack(int i, int j, int dir) {

        visited.add(new Pair(i, j));

        robot.clean();

        for(int d = 0;d<4;d++) {

            int del = (dir + d)%4; // 非常好的去解决方向的问题

            int newI = i + directions[del][0];

            int newJ = j + directions[del][1];

            if(!visited.contains(new Pair(newI, newJ)) && robot.move()) {

                backtrack(newI, newJ, del);

                goback();

            }

            robot.turnRight();

        }

    }

    public void cleanRoom(Robot robot) {

        this.robot = robot;

        backtrack(0,0,0);

    }

}

time complexity: O(N−M), where N is a number of cells in the room and M is a number of obstacles.

space complexity: O(N-M)

比较接近的一道题: 130. Surrounded Regions , 比较轻松的做法就是原地修改值,然后再改回来。

相关文章

  • 刷题(14)489. Robot Room Cleaner

    昨天刷到一个很有意思的题目,489.Robot Room Cleaner, 是hard题,我顺便看了下半年内的公司...

  • Robot Room Cleaner

    题目Given a robot cleaner in a room modeled as a grid. Each...

  • JINGCHI.AI店面利口489扫地机器人

    Given a robot cleaner in a room modeled as a grid.Each ce...

  • UPCAN X3 Smart Robot Vacuum Clea

    -UPCAN X3 Smart Robot Vacuum Cleaner Vacuuming Sweeping M...

  • Robot Vacuum Cleaner CodeForces

    题目大意:给定几个片段进行排序,使得结果中字符串“sh”出现次数最多(不需要连续),并输出。 思路是抄的:题意:给...

  • 教你怎么做一只考试锦鲤

    考试前14天疯狂刷题,各个平台疯狂刷题,刷题就对了。 刷的越多,大脑记得越多,也许你刷10道题,能记住的只有1道题...

  • 20190829:刷题14

    刷题14:以省教育厅的一名工作人员身份,就S大学举办心理健康节活动情况写一篇总结发言稿。 【结构提纲】 标题:S大...

  • [Math_Medium] 858. Mirror Reflec

    原题:858. Mirror Reflection There is a special square room ...

  • 2020-27周复盘

    上周完成情况 任务进度结果刷题14道完成刷题8道Fail完成文本分类项目的代码完成finetuneDoing将当前...

  • 刷题刷题

    时间紧迫,任务繁重,又有疫情影响,搞的人心惶惶,一时间复习得不安宁,又舍不得摆烂。 在焦灼、惶恐的情绪中,紧张急迫...

网友评论

      本文标题:刷题(14)489. Robot Room Cleaner

      本文链接:https://www.haomeiwen.com/subject/hvkuhrtx.html