day_50

98. 所有可达路径

python 复制代码
def dfs(graph, x, n, path, res):
    if x == n:
        res.append(path.copy())
        return
    for i in range(1, n + 1):
        if graph[x][i] == 1:
            path.append(i)
            dfs(graph, i, n, path, res)
            path.pop()

def main():
    n, m = map(int, input().split())
    graph = [[0] * (n + 1) for _ in range(n + 1)]
    for _ in range(m):
        s, t = map(int, input().split())
        graph[s][t] = 1 
        
    res = []
    dfs(graph, 1, n, [1], res)
    
    if not res:
        print(-1)
    else:
        for path in res:
            print(' '.join(map(str, path)))

if __name__ == '__main__':
    main()

邻接表方式

python 复制代码
from collections import defaultdict

def dfs(graph, x, n, path, res):
    if x == n:
        res.append(path.copy())
        return
    for i in graph[x]:
        path.append(i)
        dfs(graph, i, n, path, res)
        path.pop()

def main():
    n, m = map(int, input().split())
    
    graph =defaultdict(list)
    for _ in range(m):
        s, t = map(int, input().split())
        graph[s].append(t)
    
    res = []
    dfs(graph, 1, n, [1], res)
    
    if not res:
        print(-1)
    else:
        for path in res:
            print(' '.join(map(str, path)))
    
if __name__ == '__main__':
    main()

就一深搜,虽然我不能自己写出来,但是这个不难。

邻接表和邻接矩阵都只是存储图的一种方式,在存储和遍历的时候有所不同,解题思路都是一样的。

相关推荐
Js.Tx34 分钟前
【具体数学 Concrete Mathematics】2.1.5 一般性的方法
算法·具体数学
起个名字费劲死了42 分钟前
Halcon学习一:骰子识别
前端·python·学习
eric-sjq2 小时前
小思框架 · 30M 级长上下文新架构对比技术报告
人工智能·python·深度学习·语言模型
秋天的怀念_David2 小时前
算法一千零一夜 · 作品相关:版权与致谢声明
程序人生·算法·学习方法
揽星河..3 小时前
【C语言】数组
c语言·开发语言·算法
careathers3 小时前
【数据结构】基于比较的排序算法 - 选择排序
数据结构·算法·排序算法
听风若依3 小时前
C++模板初阶
c++·算法
reasonsummer3 小时前
【办公类-04-05】20261030整理手机照片(华为手机助手导出照片到日期文件夹+批量添加四级文件夹+手动转移照片更名+更改三级文件夹合并汉字名称)
python·智能手机
纪念 2293 小时前
C++ 算法(模拟)
开发语言·c++·算法
揽星河..4 小时前
【C语言】函数
c语言·算法