中级农民
- 积分
- 106
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-10-7
- 最后登录
- 1970-1-1
|
Day2
'''
Imagine a robot sitting on the upper left corner of grid with r rows and c columns.
The robot can only move in two directions, right and down, but certain cells 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.
"off limits" and empty grid are represented by 1 and 0 respectively.
Return a valid path, consisting of row number and column number of grids in the path.
Example 1:
Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: [[0,0],[0,1],[0,2],[1,2],[2,2]]
Note:
r, c <= 100
'''
这题可以用bottom-up的解法, 先看target位置(r,c),想要到达(r,c)可以先到达(r,c-1)或者(r-1,c).
可选步子只有向右和向下,因此想要到达任意位置都遵循这个准则[想要到达(r,c)可以先到达(r,c-1)或者(r-1,c)].然后输出是一条可行路径.
#Solution with recursion O(2^r+c)
def getPath(maze):
if maze == None or len(maze) == 0:
return None
path = []
if isPath(maze, len(maze)-1, len(maze[0])-1, path):
return path
return None
def isPath(maze, row, col, path):
#if out of bounds or not available, return
if col < 0 or row < 0 or not maze[row][col]:
return False
isAtOrigin = (row == 0) and (col == 0)
#if there's a path from the start to here, add my location
if isAtOrigin or isPath(maze, row, col-1, path) or isPath(maze, row-1, col,path):
point = (row,col)
path.append(point)
return True
return False
这个方法的时间复杂度O(2^r+c). 这其中的路线上会有一些重复的部分,可以作为优化的突破点.
可以考虑记录下已经访问过的节点(判定过失败的节点),使用dp的方法来做优化.
def isPathMemoized(maze, row, col, path, failedPoints): #增加failedPoints
#If out of bounds or not availabe, return
if col < 0 or row < 0 or not maze[row][col]:
return False
point = (row,col)
# if we've already visisted this cell, return
if point in failedPoints:
return False
isAtOrigin = (row == 0) and (col == 0)
#If there's a path from start to my current location, add my location
if isAtOrigin or isPathMemoized(maze, row, col-1, path, failedPoints) or isPathMemoized(maze, row-1, col, path, failedPoints):
path.append(point)
return True
failedPoints.append(point) #failedPoints 增加元素
return False
时间复杂度 O(XY),每个元素只访问一次.[疑问:XY是什么?为啥不是rc了?]
|
|