动态规划_leetcode64

#coding=utf-8

# 按递归的逆顺序 从底向上
class Solution1(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""

self.m = len(grid)
self.n = len(grid[0])


self.nextDirection = [[0,-1],[-1,0]]

self.visit = [[False for i in range(self.n)] for i in range(self.m)]

self.dp(grid)

return grid[0][0]


def inArea(self,x,y):
return x >= 0 and x < self.m and y >= 0 and y < self.n

def getDownValue(self,grid,x,y):
downX = x +1
downY = y

if self.inArea(downX,downY):
return grid[downX][downY]

return None

def getrightValue(self,grid,x,y):
rightX = x
rightY = y + 1

if self.inArea(rightX, rightY):
return grid[rightX][rightY]

return None

# grid[x][y] 表示grid[x][y] 到 grid[m][n]的最短路径
def dp(self,grid):

sX = self.m-1
sY = self.n-1



queue = []
queue.append([sX,sY])

while queue:
x, y = queue.pop(0)

if not self.visit[x][y]:

self.visit[x][y] = True

downValue = self.getDownValue(grid,x,y)
rightValue = self.getrightValue(grid,x,y)

if downValue != None and rightValue != None:
grid[x][y] = min(downValue,rightValue) + grid[x][y]

if downValue != None and rightValue == None:
grid[x][y] = downValue + grid[x][y]

if downValue == None and rightValue != None:
grid[x][y] = rightValue + grid[x][y]


for item in self.nextDirection:
nextX = x + item[0]
nextY = y + item[1]

if self.inArea(nextX,nextY):
queue.append([nextX,nextY])


print grid[0][0]



# 递归的逆顺序可以优化为 一直向上和一直向左回溯
class Solution2(object):
def minPathSum(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""

self.m = len(grid)
self.n = len(grid[0])


for x in range(self.m-1,-1,-1):
for y in range(self.n-1,-1,-1):

if x == self.m-1 and y == self.n-1:
continue
if x == self.m-1:
grid[x][y] = grid[x][y] + grid[x][y+1]
continue

if y == self.n-1:
grid[x][y] = grid[x+1][y] + grid[x][y]
continue

grid[x][y] = min(grid[x+1][y],grid[x][y+1]) + grid[x][y]

print grid[0][0]
return grid[0][0]















s = Solution2()

g = [
[1,3,1],
[1,5,1],
[4,2,1]
]


g1 = [
[9,9,0,8,9,0,5,7,2,2,7,0,8,0,2,4,8], [4,4,2,7,6,0,9,7,3,2,5,4,6,5,4,8,7], [4,9,7,0,7,9,2,4,0,2,4,4,6,2,8,0,7], [7,7,9,6,6,4,8,4,8,7,9,4,7,6,9,6,5], [1,3,7,5,7,9,7,3,3,3,8,3,6,5,0,3,6], [7,1,0,7,5,0,6,6,5,3,2,6,0,0,9,5,7], [6,5,6,3,8,1,8,6,4,4,3,4,9,9,3,3,1], [1,0,2,9,7,9,3,1,7,5,1,8,2,8,4,7,6], [9,6,7,7,4,1,4,0,6,5,1,9,0,3,2,1,7], [2,0,8,7,1,7,4,3,5,6,1,9,4,0,0,2,7], [9,8,1,3,8,7,1,2,8,3,7,3,4,6,7,6,6], [4,8,3,8,1,0,4,4,1,0,4,1,4,4,0,3,5], [6,3,4,7,5,4,2,2,7,9,8,4,5,6,0,3,9], [0,4,9,7,1,0,7,7,3,2,1,4,7,6,0,0,0]]g2 = [ [9,9,0,8,9], [4,4,2,7,6], [4,9,7,0,7], [7,7,9,6,6], [1,3,7,5,7]]g3 = [ [9,9,0,8], [4,4,2,7], [4,9,7,0], [7,7,9,6],]s.minPathSum(g1)
原文地址:https://www.cnblogs.com/lux-ace/p/10546300.html