# https://blog.csdn.net/oyall520/article/details/105418833
# https://zhuanlan.zhihu.com/p/43358393
'''stuation one'''
'''一共有多少条路径:计算到其中某个格子的路径有多少,即到他上边和左边的路径数之和(只能向右和向下)'''
def UniquePaths(m, n):
path_matrix = [[1 for i in range(n)] for j in range(m)]
for line in range(1, m):
for col in range(1, n):
path_matrix[line][col] = path_matrix[line - 1][col] + path_matrix[line][col - 1]
print(path_matrix[m - 1][n - 1])
return path_matrix[m - 1][n - 1]
'''深度优先遍历-走迷宫'''
# class Solution2:
# counter = 0
# def uniquePaths(self, m, n):
# '''
# :param m: int
# :param n: int
# :return: int
# '''
# if m != 1 and n != 1:
# self.uniquePaths(m - 1, n)
# self.uniquePaths(m, n - 1)
# if m == 1 or n == 1:
# self.counter = self.counter + 1
# print(self.counter)
# return
# a = Solution2()
# a.uniquePaths(4, 5)
'''situation three'''
'''所有路径中能取到的最大值'''
def carrots(array):
m = len(array)
n = len(array[0])
memo = [[0 for i in range(n)] for j in range(m)]
memo[0][0] = array[0][0]
for ii in range(1, m):
memo[ii][0] = memo[ii - 1][0] + array[ii][0]
for jj in range(1, n):
memo[0][jj] = memo[0][jj - 1] + array[0][jj]
for i in range(1, m):
for j in range(1, n):
memo[i][j] = max(memo[i - 1][j], memo[i][j - 1]) + array[i][j]
return memo[m - 1][n - 1]
# A = [[1,4,9],[3,5,9]]
# result = carrots(A)
# print(result)
'''situation two'''
'''有障碍时一共有多少路径可以走:加个判断条件'''
def BarrierUniquePath(array):
m = len(array)
n = len(array[0])
memo = [[1 for i in range(n)] for j in range(m)]
for ii in range(1, m):
if array[ii][0] == 1:
memo[ii][0] = 0
for jj in range(1, n):
if array[0][jj] == 1:
memo[0][jj] = 0
for line in range(1, m):
for loc in range(1, n):
if array[line][loc] == 0:
memo[line][loc] = memo[line - 1][loc] + memo[line][loc - 1]
else:
memo[line][loc] = 0
print(memo[m - 1][n - 1])
return memo[m - 1][n - 1]
A = [[0, 0, 0], [0, 0, 0], [0, 1, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
# BarrierUniquePath(A)
'''situation four'''
'''三角形的最小路径和'''
def TrianglePaths(array):
m = len(array)
if m == 0:
return 0
for line in range(len(array)-2, -1, -1):
for col in range(len(array[line])):
array[line][col] += min(array[line+1][col], array[line+1][col+1])
print(array[0][0])
return array[0][0]
B = [
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
TrianglePaths(B)
12-02
4310
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
10-06
2200
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
02-25
2218
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-24
2689
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
05-20
1万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)