13

def moveCount(threshold, rows, cols):
    if threshold <= 0 or rows == 0 or cols == 0:
        return 0
    visited = []

    for row in range(rows):
        tmp = []
        for col in range(cols):
            tmp.append(False)
        visited.append(tmp)

    count = moveCountCore(threshold, rows, cols, 0, 0, visited)
    print(visited)
    del visited
    return count


def moveCountCore(threshold, rows, cols, row, col, visited):
    count = 0
    if (check(threshold, rows, cols, row, col, visited)):
        visited[row][col] = True
        # count = 1
        # 递归找 上下左右
        count = 1 + moveCountCore(threshold, rows, cols, row - 1, col, visited) + moveCountCore(threshold, rows, cols,
                                                                                                row,
                                                                                                col - 1,
                                                                                                visited) + moveCountCore(
            threshold, rows, cols, row + 1, col, visited) + moveCountCore(threshold, rows, cols, row, col + 1, visited)

    return count


def check(threshold, rows, cols, row, col, visited):
    if col >= 0 and row >= 0 and col < cols and row < rows and getDigigSum(row + 1) + getDigigSum(
            col + 1) <= threshold and not \
            visited[row][col]:
        return True
    return False


def getDigigSum(number):
    sum = 0
    while number > 0:
        sum += number % 10
        number //= 10

    return sum


#递归的思想
#1.row col 0 0  check(0,0)=True
#赋值visited;递归-1 0 false return 0 递归0 -1 return 0 递归1 0 return 0 递归0 1
#2. row col0 1 check(0,1) true
#赋值visited【0,1】;递归 -1 1 return 0 递归1,1return 0 递归 0 0 return 0 进入递归 0 2
#3.row col 0 2 check(0,2) true
#赋值visited[0,2];递归-1 2 return 0 递归 1,2 return - 递归0 1 return 0 递归0 3 retrun 0    所以执行move(0,2)=1+0+0+0 return 1 ,返回上层函数move(0,1)=1+0+0+0+move(0,2)=2;返回上层函数move(0,0)=1+0+0+move(0,1)=3;
#最后return 3
print(moveCount(10, 1,3))

posted @ 2020-04-23 14:01  烧刘病  阅读(91)  评论(0编辑  收藏  举报
回到页首