题目描述
地上有一个m行和n列的方格
。一个机器人从坐标0,0
的格子开始移动
,每一次只能向左,右,上,下
四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k
的格子。
示例
例如,当k为18
时,机器人能够进入方格(35,37)
,因为3+5+3+7 = 18
。但是,它不能进入方格(35,38)
,因为3+5+3+8 = 19
。请问该机器人能够达到多少个格子?
分析
依然利用回溯法的子集树解空间思想。
- 确定解空间-
子集树
。 - 利用
深度优先
搜索。 - 确定
剪枝条件
。- 搜索到矩阵
边界外
,剪枝。 - 该位置已经被
搜索过了
,剪枝。 和大于K
的,剪枝。
- 搜索到矩阵
需注意 的一点是,这里搜索过的位置不需要回溯了,也就是说不在搜索这里。
代码
# -*- coding:utf-8 -*-
class Solution:
def __init__(self):
self.threshold = 0
self.assistMat = []
self.rows = 0
self.cols = 0
def conflict(self, row, col):
if self.rows>row>=0 and self.cols>col>=0 \
and sum(map(int, str(row)+str(col)))<= self.threshold \
and not self.assistMat[row][col]:
return False
return True
def findGrid(self, row, col):
count = 0
if not self.conflict(row, col):
self.assistMat[row][col] = True
count = 1 + self.findGrid(row-1, col) \
+ self.findGrid(row+1, col) \
+ self.findGrid(row, col-1) \
+ self.findGrid(row, col+1)
return count
def movingCount(self, threshold, rows, cols):
self.threshold = threshold
self.rows = rows
self.cols = cols
self.assistMat = [[False for i in range(cols)]for j in range(rows)]
return self.findGrid(0 , 0)