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

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

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

相关推荐
dinglu1030DL2 分钟前
C#怎么实现发布订阅模式 C#如何用事件总线EventBus实现模块间的松耦合消息通信【架构】
jvm·数据库·python
神明9313 分钟前
PHP函数怎样利用硬件内存压缩功能_PHP启用zswap硬件加速【指南】
jvm·数据库·python
2301_781571429 分钟前
如何配置用户的资源使用上限_MAX_QUERIES_PER_HOUR查询频率限制
jvm·数据库·python
斯内科9 分钟前
四胞胎素数:找出‌个位数分别是 1、3、7、9‌,且‌十位及更高位数字完全相同‌的质数,例如 11、13、17、19
算法·质数·素数·四胞胎素数
2501_9012005313 分钟前
编写表与字段注释后数据无法保存怎么排查_权限设置与回滚处理
jvm·数据库·python
m0_7335654626 分钟前
mysql数据库执行全量备份影响业务_利用xtrabackup实现无锁备份
jvm·数据库·python
2401_8800714031 分钟前
golang如何编写DNS查询工具_golang DNS查询工具编写大全
jvm·数据库·python
Vertira37 分钟前
python 配置PostgreSQL 数据库
开发语言·python
Hello.Reader40 分钟前
算法基础(十二)——主方法:快速求解常见递归式
算法
m0_5913647343 分钟前
JavaScript中Object-hasOwn作为现代安全检测方案
jvm·数据库·python