机器人的运动范围(python)

一,题目描述

地上有一个m行和n列的方格。一个机器人从坐标0,0的格子开始移动,每一次只能向左,右,上,下四个方向移动一格,但是不能进入行坐标和列坐标的数位之和大于k的格子。 例如,当k为18时,机器人能够进入方格(35,37),因为3+5+3+7 = 18。但是,它不能进入方格(35,38),因为3+5+3+8 = 19。请问该机器人能够达到多少个格子?
 
二,分析
(这篇随笔是为了能记住别人的代码而写的)
 
先举个栗子:有如下全是0的雪地,机器人每踩过一格,就要在上面留下数字1这个脚印,当看到有1时,机器人就不能再上这格子了
 
我们先定义一个判断函数,判断行号加列号是否大于给定的数字
def judge(self,threshold,i,j):
    if sum(map(int,str(i)+str(j)))<=threshold:
        return True
    else:
        return False
 
主函数movingCount(self, threshold, rows, cols) 就干了两件事
一是画了一片上面全是0的雪地
matrix=[[0 for i in range(cols) ]for j in range(rows)]
第二件事就是找机器人走过多少格子count
count = self.findgrid(threshold, rows, cols, matrix, 0, 0)
return count
 
count怎么找?
定义一个函数去找
def findgrid(self, threshold, rows, cols, matrix, i, j):
    我们先让count=0
然后留下脚印matrix[i][j]=1
然后求count=1+递归调用 findgrid求前后左右的count

count=1+self.findgrid(threshold, rows, cols, matrix, i+1, j) +self.findgrid(threshold, rows, cols, matrix, i-1, j) +self.findgrid(threshold, rows, cols, matrix, i, j+1) +self.findgrid(threshold, rows, cols, matrix, i, j-1)

return count

结束

三,代码

 

 

posted @ 2020-06-23 20:45  董不耀  阅读(212)  评论(0编辑  收藏  举报