代码随想录算法训练营第50天|98. 所有可达路径

1. 图论理论基础

文档讲解: 代码随想录

度:无向图中有几条边连接该节点,该节点就有几度
在有向图中,每个节点有出度和入度,出度指从该节点出发的边的个数,而入度是指向该节点边的个数

2. 98. 所有可达路径

题目链接:98. 所有可达路径
文档讲解: 代码随想录

#邻接矩阵
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()

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)))
#邻接表
from collections import defaultdict
def dfs(graph,x,n,res,path):
    #终止条件
    if x == n:
        res.append(path.copy())
        return 
    for i in graph[x]:
        #找到x指向的节点
        path.append(i)
        dfs(graph,i,n,res,path)
        path.pop()
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,res,[1])
if not res:
    print(-1)
else:
    for path in res:
        print(' '.join(map(str,path)))

3. 广度优先搜索理论基础

文档讲解: 代码随想录
广搜适合于解决两个点之间的最短路径问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值