机器人的运动范围(DFS)

题目描述

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


DFS实现,不需要回溯,找到所有的能够走的点,并不是一条路径上面的点

# -*- coding:utf-8 -*-
class Solution:
    def movingCount(self, threshold, rows, cols):
        # write code here
        vis = [[0 for y in range(cols)] for x in range(rows)]
        return self.DFS(0, 0, rows, cols, vis, threshold)
    def DFS(self, x, y, rows, cols, vis, threshold):
    	if x >= 0 and x < rows and y >= 0 and y < cols and vis[x][y] == 0 and \
    	self.Judge(x, y, threshold) == True:

	    	vis[x][y] = 1
	    	return self.DFS(x - 1, y, rows, cols, vis, threshold) + \
	    	self.DFS(x + 1, y, rows, cols, vis, threshold) + \
	    	self.DFS(x, y - 1, rows, cols, vis, threshold) + \
	    	self.DFS(x, y + 1, rows, cols, vis, threshold) + 1
        return 0

    def Judge(self, x, y, threshold):
        n = sum([int(i) for i in str(x)]) + sum([int(i) for i in str(y)])

        if n > threshold:
            return False
        return True

if __name__ == "__main__":
    a = Solution()
    print a.movingCount(8, 5, 5) # 25
    print a.movingCount(15, 20, 20) # 359

使用内部类来实现

# -*- coding:utf-8 -*-
class Solution:
    def movingCount(self, threshold, rows, cols):
        u"内部类实现"
        # write code here
        vis = [[0 for y in range(cols)] for x in range(rows)]

        def DFS(x, y):
            if x >= 0 and x < rows and y >= 0 and y < cols and vis[x][y] == 0 \
            and sum(map(int, str(x) + str(y))) <= threshold: # 使用map把字符串转化为list
                vis[x][y] = 1
                # 四个方向进行求和,每执行一次接下来的 return 说明有一个点满足条件,对应加 1
                return DFS(x - 1, y) + DFS(x + 1, y) + DFS(x, y - 1) + DFS(x, y + 1) + 1
            return 0

        return DFS(0, 0)

if __name__ == "__main__":
    a = Solution()
    print a.movingCount(8, 5, 5) # 25
    print a.movingCount(15, 20, 20) # 359


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值