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_9668714011 分钟前
Python 爬虫 + 数据挖掘实战:数据抓取与深度挖掘分析全流程
爬虫·python·数据挖掘
青禾83722 分钟前
Linux 系统信息、权限管理与 Python 并发编程(协程与线程)完全指南
linux·python
曲无忆29 分钟前
密码学三大核心技术解析
python·密码学
qq210846295330 分钟前
在python中什么是 self 和 cls?
开发语言·前端·python
nanawinona38 分钟前
2026年手工思路量化后,工具重点会怎样变化
人工智能·python
带多刺的玫瑰1 小时前
Leecode#4刷题之寻找两个正序数组的中位数
java·前端·算法
今天AI了吗1 小时前
从聊天到委派:AI Agent 如何推进长期任务
数据库·人工智能·python·sql·rust
土司大王1 小时前
LeetCode hot100——除了自身以外数组的乘积
数据结构·算法·leetcode
IvanCodes1 小时前
RAG 实战教程(三):向量数据库检索算法,KNN、IVF、HNSW 与 Faiss 实战
人工智能·算法·agent