回溯法-066-機器人的運動範圍

題目描述

地上有一個m行和n列的方格。一個機器人從座標0,0的格子開始移動,每一次只能向左,右,上,下四個方向移動一格,但是不能進入行座標和列座標的數位之和大於k的格子。

示例

例如,當k爲18時,機器人能夠進入方格(35,37),因爲3+5+3+7 = 18。但是,它不能進入方格(35,38),因爲3+5+3+8 = 19。請問該機器人能夠達到多少個格子?

分析

依然利用回溯法的子集樹解空間思想

  1. 確定解空間-子集樹
  2. 利用深度優先搜索。
  3. 確定剪枝條件
    1. 搜索到矩陣邊界外,剪枝。
    2. 該位置已經被搜索過了,剪枝。
    3. 和大於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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章