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

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

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

相关推荐
FreakStudio1 小时前
一文速通 Python 并行计算:13 Python 异步编程-基本概念与事件循环和回调机制
python·pycharm·协程·多进程·并行计算·异步编程
豌豆花下猫3 小时前
让 Python 代码飙升330倍:从入门到精通的四种性能优化实践
后端·python·ai
夏末蝉未鸣013 小时前
python transformers库笔记(BertForTokenClassification类)
python·自然语言处理·transformer
YuTaoShao4 小时前
【LeetCode 热题 100】141. 环形链表——快慢指针
java·算法·leetcode·链表
小小小新人121235 小时前
C语言 ATM (4)
c语言·开发语言·算法
weixin_418813875 小时前
Python-可视化学习笔记
笔记·python·学习
Danceful_YJ5 小时前
4.权重衰减(weight decay)
python·深度学习·机器学习
你的冰西瓜5 小时前
C++排序算法全解析(加强版)
c++·算法·排序算法
এ᭄画画的北北6 小时前
力扣-31.下一个排列
算法·leetcode