class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
def count(num) -> int:
result = 0
while num:
result += num % 10
num = int(num / 10)
return result
# 访问标记
visited = []
for i in range(m):
visited.append([0] * n)
self.result = 0
def dfs(i, j) -> int:
if not (0 <= i < m) or not (0 <= j < n) or not ((count(i) + count(j)) <= k) or visited[i][j] == 1:
return 0
else:
# 首先压栈做访问标记,result加一
# 之后对四个方位进行访问,然后逐个出栈
# 因为最后的目的是求所有能访问到的格子,所以做简单的访问标记就可以,得益于正方形的结构
# 这种递归结构把所有的方格都走了一个遍
visited[i][j] = 1
self.result += 1
dfs(i + 1, j)
dfs(i - 1, j)
dfs(i, j + 1)
dfs(i, j - 1)
return self.result
return dfs(0, 0)
solu = Solution()
x = solu.movingCount(2, 3, 17)
print(x)