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

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

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

相关推荐
骑士雄师8 分钟前
18.4 长期记忆可修改版
python
~小先生~24 分钟前
Python从入门到放弃(一)
开发语言·python
天佑木枫1 小时前
第2天:变量与数据类型 —— 让程序记住信息
python
小宋加油啊1 小时前
机械臂抓取物体 PVN3D算法调研学习
学习·算法·3d
lqqjuly1 小时前
前沿算法深度解析(一)
算法
Dust-Chasing2 小时前
Claude Code源码剖析 - Claude Code 上下文压缩机制
人工智能·python·ai
小欣加油2 小时前
leetcode1926 迷宫中离入口最近的出口
数据结构·c++·算法·leetcode·职场和发展
Cloud_Shy6183 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第五章 Item 33 - 35)
开发语言·人工智能·笔记·python·学习方法
abcy0712133 小时前
python pandas csv异步后台清洗前端优先返回成功信息
前端·python·pandas