剑指offer66.机器人的运动范围

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36811967/article/details/87931916

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

注意是从0,0开始的:

# -*- coding:utf-8 -*-
class Solution:
    def movingCount(self, threshold, rows, cols):
        # write code here
        locs = []
        def sum_num(a, b):
            return sum(list(map(int, list(str(a)))))+sum(list(map(int, list(str(b)))))
        def helper(x, y):
            if [x, y] in locs:
                return
            if x<0 or x>=rows or y<0 or y>=cols:
                return
            if sum_num(x, y) <= threshold:
                locs.append([x, y])
                helper(x-1, y)
                helper(x+1, y)
                helper(x, y-1)
                helper(x, y+1)
        helper(0, 0)
        return len(locs)

猜你喜欢

转载自blog.csdn.net/sinat_36811967/article/details/87931916
今日推荐