回溯法-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)
发布了219 篇原创文章 · 获赞 85 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/z_feng12489/article/details/102990751
今日推荐