矩阵路径(python)

m行n列的矩阵,从左上是起点,到右下的最短路径

 1 def best_path(matrix):
 2     i = len(matrix)    # 行数
 3     j = len(matrix[0])  # 列数
 4     # 建立一个标志矩阵  代表着我们当前往哪里走
 5     direction = [[None for k in range(j)] for m in range(i)]
 6     direction[0][0] = '起点'
 7     for k in range(1, j):
 8         matrix[0][k] += matrix[0][k-1]
 9         direction[0][k] = '向左'
10     for m in range(1, i):
11         matrix[m][0] += matrix[m-1][0]
12         direction[m][0] = '向上'
13     for k in range(1, j):
14         for m in range(1, i):
15             temp = min(matrix[m-1][k], matrix[m][k-1])
16             if temp == matrix[m][k-1]:
17                 direction[m][k] = '向左'
18             if temp == matrix[m-1][k]:
19                 direction[m][k] = '向上'
20             matrix[m][k] += temp
21     for d in direction:
22         print(d)
23     return matrix, direction
24 def print_path(direction):
25     path = []
26     i = len(direction) -1
27     j = len(direction[0])-1
28     while i > 0 and j > 0:
29         if direction[i][j] == '向左':
30             j -= 1
31             path.append('向左')
32         if direction[i][j] == '向上':
33             i -= 1
34             path.append('向上')
35     path.append('起点')
36     return path
37 if __name__ == '__main__':
38     matrix = [[2, 3, 1, 4, 4],
39               [2, 1, 4, 5, 3],
40               [3, 0, 2, 3, 6],
41               [4, 3, 2, 0, 8],
42               [4, 2, 0, 2, 1]]
43     matrix_, direction = best_path(matrix)
44  
45     # 打印路径
46     path = print_path(direction)
47     print("从终点会起点的路径:", path)
posted @ 2020-01-09 14:13  Assange  阅读(888)  评论(0编辑  收藏  举报