# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here
if rows<1 or cols<1 or threshold<0:
return 0
visited=[False for i in range(rows*cols)]
count=self.dp(threshold, rows, cols,visited,0,0)
return count
def dp(self,threshold, rows, cols,visited,r,c):
count=0
if r>=0 and r<rows and c>=0 and c<cols and not visited[r*cols+c]and self.count(r)+self.count(c)<=threshold:
visited[r*cols+c]=True
count=1+self.dp(threshold, rows, cols,visited,r+1,c)+self.dp(threshold, rows, cols,visited,r-1,c)+self.dp(threshold, rows, cols,visited,r,c+1)+self.dp(threshold, rows, cols,visited,r,c-1)
return count
def count(self,index):
num=0
while(index>0):
num+=index%10
index=index//10
return num