忍不住感叹自己太过naive。一开始想的极为简单:遍历矩阵,判断是否满足k条件。但是提交不过去,于是发现陷阱。
当机器人因为k条件不能通过时,会导致一些点,机器人无法继续到达(因为只能前后左右运动)
于是换个思路,一步一步的走。走一步之后判断他的四个方向是否可前行(不行就空着)然后走到下一个点,继续如此判断(走过的点flag置1,避免重复计算)。
class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
# 计算位数的和
def sum(a, b):
sum = 0
while a:
sum += a % 10
a //= 10
while b:
sum += b % 10
b //= 10
return sum
from collections import deque
flag = [[0 for _ in range(n)] for _ in range(m)]
# flag矩阵 判断机器人是否到达,已到达为1
flag[0][0] = 1
# 0,0位置设为1
temp = deque()
temp.append([0, 0])
res = 0
while temp:
temp_point = temp.popleft()
res += 1
x, y = temp_point
for x_bias, y_bias in [[0, 1], [0, -1], [1, 0], [-1, 0]]:
new_x = x + x_bias
new_y = y + y_bias
if new_x < 0 or new_x > m - 1 or new_y < 0 or new_y > n - 1 or sum(new_x, new_y) > k or flag[new_x][new_y] == 1:
continue
flag[new_x][new_y] = 1
temp.append([new_x, new_y])
return res