题目:地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
示例:
输入:5,10,10
输出:21
思路:从左上角开始移动,仅靠向左或向下移动即可遍历所有的点。遍历过的点加入set,同时用两个变量分别存储两个坐标各个数位的和,当向左移动时,即j+1, sj+1,注意当个位为9时,+1后各位变成0,十位进位+1,因此sj-8.
code:
# -*- coding:utf-8 -*-
class Solution:
def movingCount(self, threshold, rows, cols):
# write code here
vis = set()
def helper(i,j,si,sj):
if not i > -1 or not j > -1 or not i < rows or not j < cols or si + sj > threshold or (i,j) in vis:
return 0
vis.add((i,j))
return 1 + helper(i+1,j,si+1 if (i + 1)%10 else si - 8,sj) + helper(i,j+1,si,sj+1 if (j + 1)%10 else sj - 8) + helper(i-1,j,si-1 if (i>0 and i%10) else si + 8, sj) + helper(i, j-1, si, sj-1 if (j>0 and j%10) else sj +8)
return helper(0, 0, 0, 0)