机器人房间清扫
Robot Room Cleaner
题目详情
问题:机器人房间清扫
考察:递归、图
来源:Citadel
链接:https://www.jointaro.com/interviews/questions/robot-room-cleaner/
You are controlling a robot that is located somewhere in a room. The room is modeled as a grid of cells, where each cell can be free or blocked.
The robot can move forward, turn left, or turn right. When you command the robot to move forward, it moves one cell in the direction it is facing.
The robot cannot enter blocked cells.
Given the room in a grid format, your task is to clean all the free cells. The robot starts at an unknown location, facing up.
For simplicity, assume:
- The room is rectangular and has no obstacles on the boundary.
- The robot initial position is always a free cell.
- The robot cleans the cell it is on after each move.
- Assume the initial position of the robot is always (0, 0).
Interface:
interface Robot {
// returns true if next cell is open and robot moves into the cell.
// returns false if next cell is blocked and robot stays on the current cell.
boolean move();
// Robot will stay on the same cell after calling rotateLeft/rotateRight.
// Each turn will be 90 degrees.
void rotateRight();
void rotateLeft();
// Clean the current cell.
void clean();
}
Example:
Input:
room = [
[1,1,1,1,1,1,1,1],
[1,0,1,1,1,1,1,1],
[1,1,1,0,1,1,1,1],
[1,1,1,1,0,1,1,1],
[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 (1, 3).
From that point, the robot can clean all accessible cells.
Note:
- The input is only logically given. You need to write the implementation of the
Robotclass. - You are given the room in terms of a 2D grid, but you do not have access to the actual
roomdirectly.
解析
思路:在未知地图上做 DFS 回溯。记录相对坐标 visited,每次尝试四个方向;若能前进就递归清扫,返回时执行转身、前进、转身恢复原位置和朝向。
复杂度:每个可达格子访问一次,时间 O(R),空间 O(R)。