面試13題:
題目:機器人的運動范圍
題:地上有一個m行和n列的方格。一個機器人從坐標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行坐標和列坐標的數位之和大於k的格子。 例如,當k為18時,機器人能夠進入方格(35,37),因為3+5+3+7 = 18。但是,它不能進入方格(35,38),因為3+5+3+8 = 19。請問該機器人能夠達到多少個格子?
解題思路:回溯法、遞歸
解題代碼:
# -*- coding:utf-8 -*- class Solution: def movingCount(self, threshold, rows, cols): # write code here if threshold<0 or rows<1 or cols<1: return 0 markmatrix=[False]*(rows*cols) count=self.movingCountCore(threshold,rows,cols,0,0,markmatrix) return count def movingCountCore(self,threshold,rows,cols,row,col,markmatrix): value=0 if self.check(threshold,rows,cols,row,col,markmatrix): markmatrix[row*cols+col]=True value = 1+ self.movingCountCore(threshold, rows, cols, row-1, col, markmatrix)+ \ self.movingCountCore(threshold, rows, cols, row+1, col, markmatrix) + \ self.movingCountCore(threshold, rows, cols, row, col-1, markmatrix) + \ self.movingCountCore(threshold, rows, cols, row, col+1, markmatrix) return value def check(self,threshold,rows,cols,row,col,markmatrix): if row >= 0 and row < rows and col >= 0 and col < cols and \ self.getDigitNum(row)+self.getDigitNum(col)<=threshold and not markmatrix[row*cols+col]: return True return False def getDigitNum(self,number): sum=0 while(number>0): sum+=number%10 number=number//10 return sum