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:
扫地机器人。
房间(用格栅表示)中有一个扫地机器人。格栅中的每一个格子有空和障碍物两种可能。
扫地机器人提供4个API,可以向前进,向左转或者向右转。每次转弯90度。
当扫地机器人试图进入障碍物格子时,它的碰撞传感器会探测出障碍物,使它停留在原地。
请利用提供的4个API编写让机器人清理整个房间的算法。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/robot-room-cleaner
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路是DFS。这道题既然是模拟扫地机器人,那么DFS其实是蛮直观的。可以用BFS做吗?不能。因为BFS做是没法回到原点的。
这道题大部分的实现都还是比较直观的,需要注意以下几点
时间O(mn) - 遍历的坐标,应该是一个二维的房间吧
空间O(n) - hashset
Java实现
1 class Solution { 2 // the order of the directions matters 3 private int[][] dirs = new int[][] { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } }; 4 5 public void cleanRoom(Robot robot) { 6 HashSet<String> visited = new HashSet<>(); 7 int[] cur = new int[] { 0, 0 }; 8 dfs(robot, cur, 0, visited); 9 } 10 11 private void dfs(Robot robot, int[] cur, int dir, HashSet<String> visited) { 12 robot.clean(); 13 visited.add(cur[0] + "-" + cur[1]); 14 for (int i = 0; i < dirs.length; i++) { 15 int nextDir = (dir + i) % 4; 16 int[] next = new int[] { cur[0] + dirs[nextDir][0], cur[1] + dirs[nextDir][1] }; 17 if (!visited.contains(next[0] + "-" + next[1]) && robot.move()) { 18 dfs(robot, next, nextDir, visited); 19 robot.turnRight(); 20 robot.turnRight(); 21 robot.move(); 22 robot.turnLeft(); 23 } else { 24 robot.turnRight(); 25 } 26 } 27 } 28 }
[LeetCode] 489. Robot Room Cleaner
原文:https://www.cnblogs.com/cnoodle/p/13364175.html