机器人的运动范围DFS、BFS两种解法(python)

题目

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

这是一个搜索问题,可以用深度优先搜索(DFS)和广度优先搜索(BFS)两种方法解决。

DFS

def movingCount(self, threshold, rows, cols):
        move = [[0, 1], [1, 0]]
        mark = [[0] * cols for _ in range(rows)]

        def weisum(n):
            t = 0
            while n != 0:
                t = t + n % 10
                n = n // 10
            return t

        def back(x, y):
            s = 0
            if 0 <= x < rows and 0 <= y < cols and mark[x][y] == 0:
                if weisum(x) + weisum(y) <= threshold:
                    mark[x][y] = 1
                    s=1
                    for i in range(len(move)):
                        s += back(x + move[i][0], y + move[i][1]) 
            return s

        return back(0, 0)

DFS是回溯算法,每次到达一个格子后分别向右向下继续搜索,遇到障碍就返回到前一个格子。这里要注意python不能传址,格子总数s只能用返回值的形式累加。

BFS

def movingCount(self, threshold, rows, cols):
        def weisum(n):
            t = 0
            while n != 0:
                t = t + n % 10
                n = n // 10
            return t
        re = set()
        que = []
        que.append((0, 0))
        while que:
            temp = que.pop(0)
            if temp not in re:
                x,y=temp
                if 0 <= x < rows and 0 <= y < cols and weisum(
                        x) + weisum(y) <= threshold:
                    re.add(temp)
                    que.append((x+1,y))
                    que.append((x,y+1))
        return len(re)

BFS方法是用一个集合存储所有的格子坐标。先将(0,0)入队列,当队列不为空时,出队首元素,判断是否符合要求,符合则将该元素的右元素和下元素依次入队列。最后返回集合长度。
这里队列用的是list,也可以用python中的Queue类。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python中,DFS(深度优先搜索)和BFS(广度优先搜索)可以通过使用列表和字典来实现。在DFS中,我们使用栈来保存遍历的节点,而在BFS中,我们使用队列来保存节点。下面是一些Python代码示例: 1. BFS的实现: ```python graph = { "A": ["B", "C"], "B": ["A", "C", "D"], "C": ["A", "B", "D", "E"], "D": ["B", "C", "E", "F"], "E": ["C", "D"], "F": ["D"] } def BFS(graph, s): queue = [] queue.append(s) seen = [] seen.append(s) while len(queue) > 0: vertex = queue.pop(0) nodes = graph[vertex] for node in nodes: if node not in seen: queue.append(node) seen.append(node) print(vertex) BFS(graph, "A") ``` 2. DFS的实现: ```python def DFS(graph, s): stack = [] stack.append(s) seen = [] seen.append(s) while len(stack) > 0: vertex = stack.pop() nodes = graph[vertex] for node in nodes: if node not in seen: stack.append(node) seen.append(node) print(vertex) DFS(graph, "A") ``` 对于BFS,我们还可以通过添加一个映射表(字典)来记录从起始点到其他所有点的路径。下面是一个对BFS的扩展,使用字典来记录父节点的信息,从而实现找到最短路径的功能: ```python def BFS(graph, s): queue = [] queue.append(s) seen = [] seen.append(s) parent = {s: None} while len(queue) > 0: vertex = queue.pop(0) nodes = graph[vertex] for node in nodes: if node not in seen: queue.append(node) seen.append(node) parent[node = vertex print(vertex) return parent parent = BFS(graph, "A") v = "E" while v != None: print(v) v = parent[v] ``` 希望这些代码能够帮助你理解Python中的DFSBFS算法。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Python BFSDFS算法](https://blog.csdn.net/qq_43540763/article/details/115144191)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值