[LeetCode] 489. Robot Room Cleaner 扫地机器人

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

Each cell in the grid can be empty or blocked.

The robot cleaner with 4 given APIs can move forward, turn left or turn right. Each turn it made is 90 degrees.

When it tries to move into a blocked cell, its bumper sensor detects the obstacle and it stays on the current cell.

Design an algorithm to clean the entire room using only the 4 given APIs shown below.

interface Robot {
  // returns true if next cell is open and robot moves into the cell.
  // returns false if next cell is obstacle and robot stays on the current cell.
  boolean move();

  // Robot will stay on the same cell after calling turnLeft/turnRight.
  // Each turn will be 90 degrees.
  void turnLeft();
  void turnRight();

  // Clean the current cell.
  void clean();
}

Example:

Input:
room = [
  [1,1,1,1,1,0,1,1],
  [1,1,1,1,1,0,1,1],
  [1,0,1,1,1,1,1,1],
  [0,0,0,1,0,0,0,0],
  [1,1,1,1,1,1,1,1]
],
row = 1,
col = 3

Explanation:
All grids in the room are marked by either 0 or 1.
0 means the cell is blocked, while 1 means the cell is accessible.
The robot initially starts at the position of row=1, col=3.
From the top left corner, its position is one row below and three columns right.

Notes:

  1. The input is only given to initialize the room and the robot‘s position internally. You must solve this problem "blindfolded". In other words, you must control the robot using only the mentioned 4 APIs, without knowing the room layout and the initial robot‘s position.
  2. The robot‘s initial position will always be in an accessible cell.
  3. The initial direction of the robot will be facing up.
  4. All accessible cells are connected, which means the all cells marked as 1 will be accessible by the robot.
  5. Assume all four edges of the grid are all surrounded by wall.

Companies: Google, Facebook

Related Topics: Depth-first Search

Similar Questions: Walls and Gates

给一个扫地机器人和一个用网格表示的屋子,每个格子是0或者1, 0表示是障碍物,1表示可以通过。机器人有move() ,turnLeft(),turnRight(),clean() 4个API,设计一个算法把整个屋子扫一遍。

注意:房间的布局和机器人的初始位置都是不知道的。机器人的初始位置一定在可以通过的格子里。机器人的初始方向是向上。所以可以通过的格子是联通的。假设网格的四周都是墙。

解法:DFS + Backtracking

Different from regular dfs to visit all, the robot move() function need to be called, backtrack needs to move() manually and backtracking path shold not be blocked by visited positions
- IMPORTANT: Mark on the way in using set, but `backtrack directly without re-check against set`
- Backtrack: turn 2 times to revert, move 1 step, and turn 2 times to revert back.

Java:

class Solution {
    int[] dx = {-1, 0, 1, 0};
    int[] dy = {0, 1, 0, -1};
    public void cleanRoom(Robot robot) {
        // use ‘[email protected]‘ mark visited nodes, where x,y are integers tracking the coordinates
        dfs(robot, new HashSet<>(), 0, 0, 0); // 0: up, 90: right, 180: down, 270: left
    }

    public void dfs(Robot robot, Set<String> visited, int x, int y, int curDir) {
    	String key = x + "@" + y;
    	if (visited.contains(key)) return;
        visited.add(key);
    	robot.clean();

    	for (int i = 0; i < 4; i++) { // 4 directions
    		if(robot.move()) { // can go directly. Find the (x, y) for the next cell based on current direction
    			dfs(robot, visited, x + dx[curDir], y + dy[curDir], curDir);
                backtrack(robot);
    		} 

            // turn to next direction
    		robot.turnRight();
    		curDir += 1;
    		curDir %= 4;
    	}
    }

    // go back to the starting position
    private void backtrack(Robot robot) {
        robot.turnLeft();
        robot.turnLeft();
        robot.move();
        robot.turnRight();
        robot.turnRight();
    }
}  

Java:

class Solution {
    public void cleanRoom(Robot robot) {
        // use ‘[email protected]‘ mark visited nodes, where x,y are integers tracking the coordinates
        dfs(robot, new HashSet<>(), 0, 0, 0); // 0: up, 90: right, 180: down, 270: left
    }

    public void dfs(Robot robot, Set<String> visited, int i, int j, int curDir) {
    	String key = i + "@" + j;
    	if (visited.contains(key)) return;
        visited.add(key);
    	robot.clean();

    	for (int n = 0; n < 4; n++) { // 4 directions
    		if(robot.move()) { // can go directly. Find the (x, y) for the next cell based on current direction
    			int x = i, y = j;
    			switch(curDir) {
    				case 0: // go up, reduce i
    					x = i-1;
    					break;
    				case 90: // go right
    					y = j+1;
    					break;
    				case 180: // go down
    					x = i+1;
    					break;
    				case 270: // go left
    					y = j-1;
    					break;
    				default:
    					break;
    			}

    			dfs(robot, visited, x, y, curDir);
                backtrack(robot);
    		} 

            // turn to next direction
    		robot.turnRight();
    		curDir += 90;
    		curDir %= 360;
    	}
    }

    // go back to the starting position
    private void backtrack(Robot robot) {
        robot.turnLeft();
        robot.turnLeft();
        robot.move();
        robot.turnRight();
        robot.turnRight();
    }
}

Python:

class Solution(object):
    def cleanRoom(self, robot):
        """
        :type robot: Robot
        :rtype: None
        """
        directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]

        def goBack(robot):
            robot.turnLeft()
            robot.turnLeft()
            robot.move()
            robot.turnRight()
            robot.turnRight()

        def dfs(pos, robot, d, lookup):
            if pos in lookup:
                return
            lookup.add(pos)

            robot.clean()
            for _ in directions:
                if robot.move():
                    dfs((pos[0]+directions[d][0],
                         pos[1]+directions[d][1]),
                        robot, d, lookup)
                    goBack(robot)
                robot.turnRight()
                d = (d+1) % len(directions)

        dfs((0, 0), robot, 0, set())  

C++:

/**
 * // This is the robot‘s control interface.
 * // You should not implement it, or speculate about its implementation
 * class Robot {
 *   public:
 *     // Returns true if the cell in front is open and robot moves into the cell.
 *     // Returns false if the cell in front is blocked and robot stays in the current cell.
 *     bool move();
 *
 *     // Robot will stay in the same cell after calling turnLeft/turnRight.
 *     // Each turn will be 90 degrees.
 *     void turnLeft();
 *     void turnRight();
 *
 *     // Clean the current cell.
 *     void clean();
 * };
 */
class Solution {
public:
    //unordered_map<int, unordered_map<int, int>> data;
    set<pair<int,int>> s;
    int x=0;
    int y=0;
    int dx[4]={1, 0, -1, 0};
    int dy[4]={0, 1, 0, -1};
    int dir=0;
    void cleanRoom(Robot& robot) {
        /*if(data[x][y]==1){
            return;
        }
        data[x][y]=1;*/
        if(s.count({x,y})) return;
        s.insert({x,y});
        robot.clean();
        for(int i=0; i<4; i++){
            if(robot.move()){
                x+=dx[dir];
                y+=dy[dir];
                cleanRoom(robot);
                robot.turnRight();
                robot.turnRight();
                robot.move();
                robot.turnRight();
                robot.turnRight();
                x-=dx[dir];
                y-=dy[dir];
            }
            robot.turnRight();
            dir=(dir+1)%4;
        }
    }
};

  

原文地址:https://www.cnblogs.com/lightwindy/p/9739158.html

时间: 2024-07-31 17:00:38

[LeetCode] 489. Robot Room Cleaner 扫地机器人的相关文章

489. Robot Room Cleaner - Hard

Given a robot cleaner in a room modeled as a grid. Each cell in the grid can be empty or blocked. The robot cleaner with 4 given APIs can move forward, turn left or turn right. Each turn it made is 90 degrees. When it tries to move into a blocked cel

leetcode 874 Robot Simulation

leetcode 874 Robot Simulation 限制:32MB, 1s 描述 A robot on an infinite grid starts at point (0, 0) and faces north. The robot can receive one of three possible types of commands: -2: turn left 90 degrees -1: turn right 90 degrees 1 <= x <= 9: move forw

扫地机器人动画原理

使用jQuery制作一个扫地机器人动画.动画效果是画面的左边是一些垃圾,然后画面左右是一个扫地机器人,扫地机器人从右边移动到左边,然后被扫过的垃圾就会被吸到扫地机器人里面而消失掉. 理论原理:通过判断垃圾元素的坐标与扫地机器人的坐标的关系来判断垃圾是否被扫地机器人扫过,然后被扫过的垃圾就要被隐藏掉. 实现原理:使用jQuery的animate()函数进行小幅度的移动,然后使用animate()的callback回调函数,每移动一次就判断一次垃圾是否已经被扫地机器人扫过,扫过的垃圾就要被隐藏.然后

扫地机器人辞职做快递?200亿件/年大市场很蓝

近日,快递分拣机器人的一段视频在网上走红,在之后央视报道中,这段走红的快递分拣机器人作业视频里,一些装备着橙色托盘的机器人迅速穿梭,将一件件包裹运送到指定位置,完成分拣-- 文/张书乐 TMT行业观察者.游戏产业时评人,人民网.人民邮电报专栏作者 在中国,每年的快递数超过200亿件,这是一个庞大且依然快速增长的市场.如果机器人.无人机都送上快递呢? 一些网友对此揶揄到:扫地机器人辞职干快递了. 对,这个揶揄其实已经切中了要害.仅仅就无人机和机器人来说,目前对它们的应用有很多,如亚马逊.京东用无人

扫地机器人是如何击败吸尘器的?

吸尘器的种类随着社会不断的发展,人们的生活水平不断的提高,人们对于吸尘器的选择也是非常重视而逐渐的增多,不仅仅有吸尘器,还有扫地机器人(机器人吸尘器),可谓是解放人们的双手啊!机器人吸尘器成为我们忙碌的现代生活中必备器具.由iRobot制作的Roomba是我的选择.但是,纽约时报网站"Wirecutter and Sweethome"的高级作家Liam McCabe自2013年以来一直评估测试这些产品,并表示现在有了更好的选择. Roomba是一个很强大的对手吗? 非常令人惊讶的Roo

扫地机器人在偷窥你!智能家居时代的安全恐慌

智能家居的概念近年来颇为流行,而众多巨头和创业者纷纷抢滩入局,相关的智能家居产品也如雨后春笋般出现.虽然由于标准混乱.产品价格较高.大众接受程度较低等原因导致智能家居未能全面落地,但依然在迅速进化中--巨头推出的多款智能音响就是最好的证明.但近来曝光的很多事却让人胆寒:智能家居产品竟然在偷窥你! 而这些以偷窥"为乐"的智能家居产品,有的是漏洞导致其被黑客利用,有的是制造商"居心叵测"地收集用户个人隐私数据准备出售去大捞一笔--但不管如何,智能家居时代的恐慌正在全面逼

智能扫地机器人状况与发展的趋势

智能扫地机器人项目是进来比较火的智能项目之一,该产品在2014年在国内市场和国外市场都出现了大幅度增长的趋势.特别是国内品牌科沃斯的快速增长,单品单店销量过万,吸引了众多制造业高手的加入. 关于扫地机器人的功能发展历史,不得不提到美国的两家公司,Irobot 和Neato.这两家是目前全球市场知名度最高的两家工厂,手中掌握的智能行走路线的核心技术.特别是irobot,是军工企业出生,在中国深圳有生产工厂,堪称扫地机器人的鼻祖. 国外第二军团的,扫地机器人的品牌有韩国的LG和三星,夏普也在今年加入

扫地机器人的构造及核心技术详解

扫地机器人,又称自动打扫机.智能吸尘.机器人吸尘器等,是智能家居电器的一种,能凭借一定的人工智能,自动在房间内完成地板清理工作.一般采用刷扫和真空方式,将地面杂物先吸纳进入自身的垃圾收纳盒,从而完成地面清理的功能.一般来说,将完成清扫.吸尘.擦地工作的机器人,也统一归为扫地机器人. 扫地机器人的工作原理及结构 1.工作原理 扫地机器人机身为自动化技术的可移动装置,与有集尘盒的真空吸尘装置,配合机身设定控制路径,在室内反复行走,如:沿边清扫.集中清扫.随机清扫.直线清扫等路径打扫,并辅以边刷.中央

中国消费者协会2018年4月权威发布20款扫地机器人评测试验结果!

2018年4月中国消费者协会对市场上销售的二十款扫地机器人品牌产品开展了比较试验,本次比较试验从消费者关心的角度出发,结合扫地机器人样品的特点,针对样品的安全性和清扫效果进行测试和比较.为消费者选购安全.高性能的扫地机器人产品提供客观信息. 下面我们一起来看一下吧. 一.扫地机器人样品情况说明 此次比较试验样品共计20款,均由中国消费者协会的工作人员以普通消费者身份,从北京家电卖场.京东.苏宁易购.亚马逊等网络平台购买.20款所购样品中,价格从799元-7499元不等(价格以当时购买价格为准).