楼主在职跳槽,准备期间在地里获得许多帮助,现在已经顺利上岸 F 家。准备过程中碰到很多有意思的题目,想说陆续把一些总结发回来回馈地里,顺便攒点人品。这里面没有扣米的操作,但如果你觉得获得帮助,也可以做两件事情给楼主一些正反馈,1) 为这篇总结加米
2) 为这篇总结的代码所在 repo 加 star (https://github.com/jaychsu/algorithm)。
这篇总结是关于某狗的热题,扫地机器人。但我没在面他家的时候碰到,所以从找到的面经上来看,题目如下:
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.
When it tries to move into a blocked cell,
its bumper sensor detects the obstacle and it stays on the current cell.
The 4 APIs are:
clean(): clean the current location.
turnleft(k=1): turn left k*90 degrees.
turnrigt(k=1): turn right k*90 degrees.
move(direction=None): move forward for 1 position, return False if that’s not possible.
其中关于 `move` 这个 API 看到两个版本:一个是没有 parameter,每次就朝机器人面向的方向前进一步,所以需要自己在递归中维护方向;一个是可以传 direction 进去,让机器人直接朝那个方向走一步。
手动维护方向稍微 tricky 一些,可以对照代码仔细思考以下这三句话。
- 进格子:举个实例吧,假设当前位于 O 格子,上下左右分别为 UDLR,那么我要往周围移动的方向要顺着 DFS 的特点,D -> R -> L -> U(只要是十字形的移动就行,使得能够尽可能的直走,以及递归退回来的时候能面向进来时候的反向,比如 R -> U -> D -> L 也行)。
- 换方向:比如以下代码,是对应前一步进格子的 D,也就是往下走的部分 (在 robot_cleaner.py 的 L334-L338)