python JZ13 机器人的运动范围(剑指offer)

题目要求:

在这里插入图片描述

思路:

思路1:递归遍历(伪代码)

movingCount(threshold, rows, cols) :
	根据入参定义map地图,位置(x,y)处值为1,标识可以走,0标识已经走过
	调用移动moving函数,传参(第几行,第几列,threshold,rows,cols,Map),由题意从00位置开始
	返回地图上0的数量,即为移动最大格子数
moving(当前位置第几行,当前位置第几列,threshold,rows行,cols列,Map地图):
        先将当前位置标记为走过,即该位置值从1修改为0
        如果在该点能向左走
        	如果该点没被走过并且符合要求,就向左递归
        如果在该点能向右走
        	如果该点没被走过并且符合要求,就向右递归
        如果在该点能向上走
        	该点没被走过并且符合要求,就向上递归
		如果在该点能向下走
        	该点没被走过并且符合要求,就向下递归
##### 代码如下:
思路1:
```python
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param threshold int整型
# @param rows int整型
# @param cols int整型
# @return int整型
#
class Solution:
    def movingCount(self , threshold, rows, cols):
        Map = [[1 for i in range(cols)] for j in range(rows)]
        self.moving(0,0,threshold,rows,cols,Map)
        return str(Map).count('0')
        # write code here
    def moving(self,x,y,threshold,rows,cols,Map):
        Map[x][y] = 0
        if x < rows-1:
            if Map[x+1][y] and sum([int(item) for item in list((str(x+1)+str(y)))]) <=  threshold:
                self.moving(x+1,y,threshold,rows,cols,Map)
        if 0 < x:
            if Map[x-1][y] and sum([int(item) for item in list((str(x-1)+str(y)))]) <=  threshold:
                self.moving(x-1,y,threshold,rows,cols,Map)
        if y < cols-1:
            if Map[x][y+1] and sum([int(item) for item in list((str(x)+str(y+1)))]) <=  threshold:
                self.moving(x,y+1,threshold,rows,cols,Map)
        if 0 < y:
            if Map[x][y-1] and sum([int(item) for item in list((str(x)+str(y-1)))]) <=  threshold:
                self.moving(x,y-1,threshold,rows,cols,Map)
运行效果:

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值