【广度优先搜索-中等】面试题 04.01. 节点间通路(Python版本两种解法bfs、dfs)

本文探讨了两种常用的图搜索算法——广度优先搜索(BFS)和深度优先搜索(DFS),通过实例展示了如何使用它们在给定的矩阵图中查找从起点到终点的路径。两种方法的实现细节和应用场景对比,帮助理解在实际编程中如何选择最合适的搜索策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目
在这里插入图片描述

【代码】
【方法1】思路:广度优先搜索bfs
在这里插入图片描述

class Solution:
    def findWhetherExistsPath(self, n: int, graph: List[List[int]], start: int, target: int) -> bool:
        dic={}
        for x,y in graph:
            if x not in dic:
                dic[x]=[]
            dic[x].append(y)
        queue=[start]
        while queue:
            item=queue.pop(0)
            if item==target:
                return True
            if item not in dic:
                continue
            for son in dic[item]:
                queue.append(son)
        return False

【方法2】思路:深度优先搜索dfs
在这里插入图片描述

class Solution:
    def findWhetherExistsPath(self, n: int, graph: List[List[int]], start: int, target: int) -> bool:
        dic={}
        for x,y in graph:
            if x not in dic:
                dic[x]=[]
            dic[x].append(y)
        def dfs(x,visited):
            if x==target:
                return True
            if visited[x]:
                return False
            visited[x]=True
            ans=False
            if x in dic:
                for son in dic[x]:
                    ans=ans or dfs(son,visited)
            return ans
        return dfs(start,[False]*n)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值