解题思路:这道题是要求返回所以不需要回溯,dfs+剪枝,满足条件的情况下,四个方向依次进行dfs
class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
visited = set()
di = [-1, 1, 0, 0]
dj = [0, 0, -1, 1]
def isValid(i, j):
res = 0
while(i):
res += i % 10
i //= 10
while(j):
res += j %10
j //= 10
return res <= k
def dfs(i, j):
if 0 <= i < m and 0 <= j < n and isValid(i, j) and (i, j) not in visited:
visited.add((i, j))
for k in range(4):
new_i = i + di[k]
new_j = j + dj[k]
dfs(new_i,new_j)
dfs(0, 0)
return len(visited)