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()

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

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

相关推荐
2601_962885728 分钟前
如何用 Python 计算溃疡指数(Ulcer Index)?
开发语言·python
benchmark_cc22 分钟前
如何为 QuantDash Python SDK 编写一个最小化的连接验证脚本?
python·数据分析·pandas·量化交易·股票数据·quantdash
一条闲鱼_mytube30 分钟前
分布式 ID 生成方案:雪花算法与号段模式
分布式·算法·wpf
程序边界31 分钟前
顶刊级论文配图全流程:用 Python 复刻 Nature/Science 风格图表
开发语言·python
Msir_Modern35 分钟前
Noita 元胞沙盒笔记
算法·unity·c#·游戏引擎·元胞自动机
BD_Marathon37 分钟前
【RAG项目】01、RAG项目案例介绍
python
好焊孙辉40 分钟前
螺柱焊机哪家质量好
python·fpga开发
STLearner2 小时前
KDD 2026 | (2月轮)时空数据(Spatial-Temporal)论文总结时空【下】(人群移动,城市科学(资源调度,)
大数据·人工智能·python·深度学习·机器学习·语言模型·数据挖掘
云和数据.ChenGuang2 小时前
python sorted函数详细剖析
开发语言·人工智能·windows·python·1024程序员节
木井巳2 小时前
【动态规划: 路径问题】不同路径
java·算法·leetcode·动态规划