# -*- coding:utf-8 -*-
class Solution:
    def movingCount(self, threshold, rows, cols):
        # write code here
        if threshold < 0:
            return 0
        visited = [0]*cols*rows
        result = self.movingCountCore(threshold, 0, 0 ,rows, cols, visited)
        del visited
        return result

    def movingCountCore(self, threshold, row, col ,rows, cols, visited):
        count = 0
        if self.check(threshold, row, col ,rows, cols, visited):
            visited[row * cols + col] = 1
            count = 1 + self.movingCountCore(threshold, row+1, col ,rows, cols, visited)+\
                    self.movingCountCore(threshold, row-1, col ,rows, cols, visited)+\
                    self.movingCountCore(threshold, row, col+1 ,rows, cols, visited)+\
                    self.movingCountCore(threshold, row, col-1 ,rows, cols, visited)
        return count

    def check(self, threshold, row, col ,rows, cols, visited):
        if (row >= 0 and row < rows and col >=0 and col < cols and (not visited[row * cols + col]) and ((self.getDigitSum(row)+self.getDigitSum(col))<=threshold)):
            return True
        return False

    def getDigitSum(self, number): 
        sum_ = 0
        for i in str(number):
            sum_ += int(i)
        return sum_