题目描述
地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
思路:回溯法
这个方格可以看成一个m*n的矩阵,机器人从(0,0)出发,当它准备进入坐标为(i.j)的格子时,检查坐标来判断是否能进入。如果机器人能进入(i,j)的格子,再判断它是否能进入4个相邻的格子。
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here
is_visited = [[0 for _ in range(cols)] for _ in range(rows)]
count = 0
count = self.movingCountCore(threshold, rows, cols, is_visited, 0, 0)
return count
def movingCountCore(self, threshold, rows, cols, is_visited, r, c):
count = 0
if (r>=0 and r<rows and c>=0 and c<cols and r//10+r%10+c//10+c%10<=threshold and is_visited[r][c]==0):
is_visited[r][c]=1
count = 1+ self.movingCountCore(threshold, rows, cols, is_visited, r, c-1)+self.movingCountCore(threshold, rows, cols, is_visited, r, c+1)+self.movingCountCore(threshold, rows, cols, is_visited, r-1, c)+self.movingCountCore(threshold, rows, cols, is_visited, r+1, c)
return count