题目
思路
与矩阵路径的问题类似,这个问题可以从(0,0)开始出发,每次寻找当前格子周围的4个格子是否满足条件,满足条件,则将布尔矩阵中对应的值置为1,遍历完成后,对布尔矩阵求和。
题解
def jiqi_run_path(rows, cols, k):
if rows <= 0 or cols <= 0 or k <= 0:
return 0
boolmatrix = [([0] * cols) for i in range(rows)]
for i in range(rows):
for j in range(cols):
jiqi_run_next(rows, cols, i, j, k,boolmatrix)
return sum([sum(x) for x in boolmatrix])
def jiqi_run_next( rows, cols, row, col, k,boolmatrix):
if row < 0 or row >= rows or col < 0 or col >= cols:
return False
if get_sum(row)+get_sum(col) <= k and boolmatrix[row][col] == 0:
boolmatrix[row][col] = 1
has_nex = (jiqi_run_next(rows, cols, row+1, col, k,boolmatrix)
or jiqi_run_next(rows, cols, row + 1, col, k, boolmatrix)
or jiqi_run_next(rows, cols, row + 1, col, k, boolmatrix)
or jiqi_run_next(rows, cols, row + 1, col, k, boolmatrix))
if not has_nex:
return False
def get_sum(num):
sum = 0
while num > 0:
sum += num % 10
num = num // 10
return sum
print(jiqi_run_path(3,4, 2))