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

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

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

相关推荐
YuTaoShao3 小时前
【LeetCode 每日一题】1653. 使字符串平衡的最少删除次数——(解法三)DP 空间优化
算法·leetcode·职场和发展
茉莉玫瑰花茶3 小时前
C++ 17 详细特性解析(5)
开发语言·c++·算法
cpp_25013 小时前
P10570 [JRKSJ R8] 网球
数据结构·c++·算法·题解
cpp_25013 小时前
P8377 [PFOI Round1] 暴龙的火锅
数据结构·c++·算法·题解·洛谷
uesowys3 小时前
Apache Spark算法开发指导-Factorization machines classifier
人工智能·算法
aiguangyuan4 小时前
使用LSTM进行情感分类:原理与实现剖析
人工智能·python·nlp
季明洵4 小时前
C语言实现单链表
c语言·开发语言·数据结构·算法·链表
shandianchengzi4 小时前
【小白向】错位排列|图文解释公考常见题目错位排列的递推式Dn=(n-1)(Dn-2+Dn-1)推导方式
笔记·算法·公考·递推·排列·考公
I_LPL4 小时前
day26 代码随想录算法训练营 回溯专题5
算法·回溯·hot100·求职面试·n皇后·解数独
小小张说故事4 小时前
BeautifulSoup:Python网页解析的优雅利器
后端·爬虫·python