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.
思路:这题比较难想的是,怎么找下一个方向,不能random的找,否则会陷入死循环,方法就是四个方向按照一定顺序,也就是clockwise的找,下一层的时候,收集可以move到的点,然后再返回,如果不行,机器人就turnRight(),也就是找到下一个pos,跟dx dy是一致的方向;
/**
* // This is the robot's control interface.
* // You should not implement it, or speculate about its implementation
* interface Robot {
* // 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.
* public boolean move();
*
* // Robot will stay in the same cell after calling turnLeft/turnRight.
* // Each turn will be 90 degrees.
* public void turnLeft();
* public void turnRight();
*
* // Clean the current cell.
* public void clean();
* }
*/
class Solution {
public void cleanRoom(Robot robot) {
HashSet<String> visited = new HashSet<>();
dfs(robot, 0, 0, visited, 0);
}
// 逆时针方向旋转;
private int[][] dirs = {{-1,0},{0,1},{1,0},{0,-1}};
public void dfs(Robot robot, int x, int y, HashSet<String> visited, int arrow) {
String pos = x + "-" + y;
if(visited.contains(pos)) {
return;
}
visited.add(pos);
robot.clean();
for(int k = 0; k < 4; k++) {
if(robot.move()) {
int nx = x + dirs[arrow][0];
int ny = y + dirs[arrow][1];
dfs(robot, nx, ny, visited, arrow);
// backtrack,还原原来的指向位置;
robot.turnRight();
robot.turnRight();
robot.move();
robot.turnRight();
robot.turnRight();
}
//还原之后,我立马转90度,turnRight, 就是面对下一个方向;
robot.turnRight();
arrow = (arrow + 1) % 4; // arrow随之箭头转90度,也就是箭头+1;
}
}
}