天天看点

[CareerCup] 9.2 Robot Moving 机器人移动

9.2 Imagine a robot sitting on the upper left corner of an X by Y grid. The robot can only move in two directions: right and down. How many possible paths are there for the robot to go from (0,0) to (X,Y)? 

 FOLLOW UP 

 Imagine certain spots are "off limits," such that the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to the bottom right.

解法一:

解法二:

这道题的Follow up说格子中可能有障碍物,即不能到达的位子,让我们找到一条从左上点到右下点的路径,只需一条而已,不用将所有的都找出来,那么我们使用递归来做,我们反方向走,从右下点往左上点找,我们用哈希表来记录某个位置是否访问过,当递归到原点的时候,我们把原点加入结果中,然后逐层递归返回,把路径中的点依次加入结果中,这样结果中保存的顺序就是正确的,参见代码如下: