[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:
- 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.
- The robot's initial position will always be in an accessible cell.
- The initial direction of the robot will be facing up.
- All accessible cells are connected, which means the all cells marked as 1 will be accessible by the robot.
- 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 'x@y' 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 'x@y' 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;
}
}
};
All LeetCode Questions List 题目汇总
[LeetCode] 489. Robot Room Cleaner 扫地机器人的更多相关文章
- 489. Robot Room Cleaner扫地机器人
[抄题]: Given a robot cleaner in a room modeled as a grid. Each cell in the grid can be empty or block ...
- [LeetCode] Robot Room Cleaner 扫地机器人
Given a robot cleaner in a room modeled as a grid. Each cell in the grid can be empty or blocked. Th ...
- LeetCode 489. Robot Room Cleaner
原题链接在这里:https://leetcode.com/problems/robot-room-cleaner/ 题目: Given a robot cleaner in a room modele ...
- LeetCode #657. Robot Return to Origin 机器人能否返回原点
https://leetcode-cn.com/problems/robot-return-to-origin/ 设置 flagUD 记录机器人相对于原点在纵向上的最终位置 flagRL 记录机器人相 ...
- 【BZOJ5318】[JSOI2018]扫地机器人(动态规划)
[BZOJ5318][JSOI2018]扫地机器人(动态规划) 题面 BZOJ 洛谷 题解 神仙题.不会.... 先考虑如果一个点走向了其下方的点,那么其右侧的点因为要被访问到,所以必定只能从其右上方 ...
- Hihocoder 1275 扫地机器人 计算几何
题意: 有一个房间的形状是多边形,而且每条边都平行于坐标轴,按顺时针给出多边形的顶点坐标 还有一个正方形的扫地机器人,机器人只可以上下左右移动,不可以旋转 问机器人移动的区域能不能覆盖整个房间 分析: ...
- Codeforces Round #461 (Div. 2) D. Robot Vacuum Cleaner
D. Robot Vacuum Cleaner time limit per test 1 second memory limit per test 256 megabytes Problem Des ...
- CodeForces - 922D Robot Vacuum Cleaner (贪心)
Pushok the dog has been chasing Imp for a few hours already. Fortunately, Imp knows that Pushok is a ...
- Codeforces 922 C - Robot Vacuum Cleaner (贪心、数据结构、sort中的cmp)
题目链接:点击打开链接 Pushok the dog has been chasing Imp for a few hours already. Fortunately, Imp knows that ...
随机推荐
- 攻击链路识别——CAPEC(共享攻击模式的公共标准)、MAEC(恶意软件行为特征)和ATT&CK(APT攻击链路上的子场景非常细)
结合知识图谱对网络威胁建模分析,并兼容MITRE组织的CAPEC(共享攻击模式的公共标准).MAEC和ATT&CK(APT攻击链路上的子场景非常细)等模型的接入,并从情报中提取关键信息对知识图 ...
- 关于jsp页面中name=“username”与name=“username ”的区别
我们可以仔细的观察一下,上面的name属性都等于username,但是确实存在大同小异的差距,为什么这样说呢,因为,第二个比第一个多了一个空格,在jsp中,我曾经遇到过一个情况就是两个单选按钮用同一个 ...
- Linux——CentOS7没有第二张网卡的配置信息
前言 为了一个实验做测试,在VMware中配置了环境,但是配置了双网卡后发现第二张网卡没有配置文件. 都是些基本命令就不写了,图里也有. 系统 : CentOS7.6 步骤 查看网卡信息 使用ip a ...
- django-用户浏览记录添加及商品详情页
视图函数views.py # /goods/商品id class DetailView(View): '''详情页''' def get(self, request, goods_id): '''显示 ...
- 【比赛题解】CSP2019 简要题解
D1T1 code 签到题,大家都会. 可以从高位往低位确定,如果遇到 \(1\),则将排名取反一下. 注意要开 unsigned long long. #include <bits/stdc+ ...
- LeetCode 873. Length of Longest Fibonacci Subsequence
原题链接在这里:https://leetcode.com/problems/length-of-longest-fibonacci-subsequence/ 题目: A sequence X_1, X ...
- LeetCode 1059. All Paths from Source Lead to Destination
原题链接在这里:https://leetcode.com/problems/all-paths-from-source-lead-to-destination/ 题目: Given the edges ...
- 阿里云部署自己的web服务器
阿里云部署自己的web服务器 [外链图片转存失败(img-GIKNTPPx-1564287221547)(https://upload-images.jianshu.io/upload_images/ ...
- 使用RedisDesktopManager客户端无法连接Redis服务器问题解决办法
是否遇到安装完成后连不上的问题? 那么这篇教程能解决. 执行步骤: 1.修改redis文件夹下redis.cong文件,在bind 127.0.0.1行前面加#注释掉这一行,使能远程连接(默认只能使用 ...
- ORACLE多条件的统计查询(case when)
前几天要做一个统计查询的功能,因为涉及多张表,多种条件的统计分析.一开始便想到了UNION和IF语句,然后写了1000多行代码,就为了查30条数据觉得不应该. 然后就开始百度,多种条件下的统计.然后有 ...