地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子?
示例 1:
输入:m = 2, n = 3, k = 1
输出:3
示例 2:
输入:m = 3, n = 1, k = 0
输出:1
提示:
- 1 <= n,m <= 100
- 0 <= k <= 20
Python 解答:可以只朝着下和右搜索
class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
count = 0
flag = [[0 for i in range(n)] for j in range(m)]
flag[0][0] = 1
def digit(num):
total = 0
while num > 0:
num, r = divmod(num, 10)
total += r
return total
def wfs(m, n, alist, k):
if not alist:
return
temp = []
for item in alist:
nonlocal count, flag
count += 1
up = digit(item[0]-1)
left = digit(item[1]-1)
right = digit(item[1]+1)
down = digit(item[0]+1)
midx = digit(item[0])
midy = digit(item[1])
if item[0]-1 >= 0 and flag[item[0]-1][item[1]] == 0 and up+midy <= k:
temp.append([item[0]-1, item[1]])
flag[item[0]-1][item[1]] = 1
if item[0]+1 < m and flag[item[0]+1][item[1]] == 0 and down+midy <= k:
temp.append([item[0]+1, item[1]])
flag[item[0]+1][item[1]] = 1
if item[1]-1 >= 0 and flag[item[0]][item[1]-1] == 0 and midx+left <= k:
temp.append([item[0], item[1]-1])
flag[item[0]][item[1]-1] = 1
if item[1]+1 < n and flag[item[0]][item[1]+1] == 0 and midx+right <= k:
temp.append([item[0], item[1]+1])
flag[item[0]][item[1]+1] = 1
wfs(m, n, temp, k)
wfs(m, n, [[0,0]], k)
return count
留言