地上有一个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
链接:https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof
class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
# visited = [[1] * n for _ in range(m)]
# for i in range(m):
# for j in range(n):
# if i // 10 + i % 10 + j // 10 + j % 10 <= k:
# visited[i][j] = 0
# def dfs(x, y):
# if x < 0 or x >= m or y < 0 or y >= n or visited[x][y]:
# return 0
# visited[x][y] = 1
# return 1 + dfs(x, y+1) + dfs(x+1, y)
# return dfs(0, 0)
visited = [[1] * n for _ in range(m)]
for i in range(m):
for j in range(n):
if i // 10 + i % 10 + j // 10 + j % 10 <= k:
visited[i][j] = 0
queue = collections.deque([(0,0)])
res = 0
while queue:
x, y = queue.popleft()
res += 1
for dx, dy in ((1,0),(0,1)):
nx, ny = x + dx, y + dy
if 0 <= nx <m and 0 <= ny < n and not visited[nx][ny]:
visited[nx][ny] = 1
queue.append((nx, ny))
return res
Leetcode 剑指 Offer 13. 机器人的运动范围 (每日一题 20210906)
最新推荐文章于 2022-06-18 16:13:15 发布