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

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

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

相关推荐
赵英英俊5 分钟前
Python day28
python
F_D_Z23 分钟前
【解决办法】pip install albumentations安装下载遇19kB/s超级慢细水管
linux·运维·python·pip
mortimer31 分钟前
PyInstaller打包踩坑记:从静默崩溃到柳暗花明
人工智能·python·github
吃着火锅x唱着歌1 小时前
LeetCode 1616.分割两个字符串得到回文串
算法·leetcode·职场和发展
孟大本事要学习2 小时前
算法第28天|动态规划:基础理论、斐波那契数、爬楼梯、使用最小花费爬楼梯
算法·动态规划
LastWhisperw2 小时前
音频算法基础(语音识别 / 降噪 / 分离)
算法·音视频·语音识别
lingling0092 小时前
艾利特机器人:光伏机器人如何重塑清洁能源制造新格局
大数据·人工智能·算法
流星白龙2 小时前
【C++算法】75.优先级队列_数据流中的第 K 大元素
开发语言·c++·算法
Monkey的自我迭代2 小时前
python线性回归:从原理到实战应用
开发语言·python·机器学习
刚入坑的新人编程2 小时前
暑期算法训练.10
数据结构·c++·算法·排序算法