php 机器人的运动范围,剑指offer:机器人的运动范围

论坛 期权论坛 编程之家     
选择匿名的用户   2021-5-28 19:39   11   0

题目描述

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?

class Solution:

def movingCount(self, threshold, rows, cols):

# 判断(row, col)是否可以进入:位置合法且未进入过

def isValid(row, col):

if row < 0 or row >= rows or col < 0 or col >= cols:

return False

num = 0

while row > 0:

num += row % 10

row //= 10

while col > 0:

num += col % 10

col //= 10

return num <= threshold

def helper(row, col):

cnt = 0 # 对于每个位置,在确认过可以访问之前先初始化为0

if isValid(row, col) and not visited[row][col]:

# 如果(row, col)可以进入,那么将其设为已访问,然后对四个邻居进行访问

visited[row][col] = True

cnt = (1 + helper(row + 1, col) + helper(row - 1, col)

+ helper(row, col + 1) + helper(row, col - 1))

return cnt

if threshold < 0:

return 0

visited = [[False] * cols for _ in range(rows)]

return helper(0, 0)

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP