class Solution:
def movingCount(self, m: int, n: int, k: int) -> int:
seen = set()
def dfs(i, j):
if (i, j) in seen:
return
if not 0 <= i < m or not 0 <= j < n:
return
total = 0
ti, tj = i, j
while ti:
total += ti - (ti // 10) * 10 if ti > 9 else ti
ti = ti // 10
while tj:
total += tj - (tj // 10) * 10 if tj > 9 else tj
tj = tj // 10
if total > k:
return
seen.add((i, j))
dfs(i - 1, j)
dfs(i + 1, j)
dfs(i, j - 1)
dfs(i, j + 1)
dfs(0, 0)
return len(seen)