LeetCode 489. Robot Room Cleaner--C++,Python解法

该博客介绍了如何解决LeetCode上的489题——Robot Room Cleaner,强调了在不知道房间布局和机器人初始位置的情况下,仅使用四个给定的API来清洁整个房间的算法设计。难点在于遍历所有可达单元格,解决方案涉及到迷宫求解的右手规则和回溯法。博主分享了Python和C++两种解法。
摘要由CSDN通过智能技术生成

题目地址:Robot Room Cleaner - LeetCode


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.


这道题目的难点在于如何顺利地把所有点都遍历一遍。如果知道迷宫求解的右手规则,以及回溯法,那么这道题目就可以做出来了。

Python解法如下:

# """
# This is the robot's control interface.
# You should not implement it, or speculate about its implementation
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值