題目描述
地上有一個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)