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

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

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

相关推荐
迷途呀3 分钟前
新闻头条后端:新闻缓存模块
前端·redis·python·缓存·fastapi
星释7 分钟前
鸿蒙智能体开发实战:35.鸿蒙壁纸大师 - 调用火山引擎模型生成壁纸
算法·华为·ai·harmonyos·鸿蒙·火山引擎
想会飞的蒲公英8 分钟前
逻辑回归为什么叫回归,却用来做分类
人工智能·python·分类·回归·逻辑回归
geovindu18 分钟前
go: Floyd-Warshall Algorithms
开发语言·后端·算法·golang
CoderYanger23 分钟前
视频裁剪+缩放+自动添加水印脚本(Python版)
开发语言·后端·python·程序人生·职场和发展·音视频·学习方法
db_murphy26 分钟前
机器学习决策树的基尼系数是个啥?
学习·算法
霍格沃兹测试开发学社测试人社区30 分钟前
Node.js 浏览器引擎 + Python 大脑:Playwright 混合架构爬虫系统深度解析
python·架构·node.js
拳里剑气33 分钟前
C++算法:优先级队列
开发语言·c++·算法·优先级队列
Turbo正则43 分钟前
机器学习入门笔记 | 基础算法及其应用场景
笔记·算法·机器学习
东华万里1 小时前
第37篇 手撕二叉树与堆的底层逻辑
数据结构·算法