- 论坛徽章:
- 0
|
代码:
#!/usr/bin/env python
def value(lst):
i = j = 0;
for i in range(1,len(lst[0])):
lst[0][i]+=lst[0][i-1]
for i in range(1,len(lst)):
lst[i][0]+=lst[i-1][0]
for i in range(1,len(lst)):
for j in range(1,len(lst[0])):
lst[i][j] += max(lst[i-1][j],lst[i][j-1])
max_value = lst[i][j] #最大值
path = [] #逆向寻找最大值路径,path存储相应坐标
path.append((i+1,j+1))
while i > 1 and j>1:
if lst[i-1][j]>lst[i][j-1]:
i = i-1
else:
j = j-1
path.append((i+1,j+1))
if i > 1:
for x in range(i-1,-1,-1):
path.append((x+1,2))
elif j > 1:
for x in range(j-1,-1,-1):
path.append((2,x+1))
path.append((1,1))
print "Max Value: %d" % max_value
print "Path:",path[::-1]
def main():
arr=[[2,2,3,0],[0,3,1,1],[1,2,2,1],[4,1,2,2]]
value(arr)
if __name__ == '__main__':
main() |
>>>
Max Value: 15
Path: [(1, 1), (1, 2), (2, 2), (3, 2), (3, 3), (4, 3), (4, 4)] |
动态规划,对于N*N的矩阵,时间复杂度为 O(N*N)
[ 本帖最后由 千年沉寂 于 2009-5-6 13:54 编辑 ] |
|