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. 广度优先搜索理论基础
文档讲解: 代码随想录
广搜适合于解决两个点之间的最短路径问题。
876

被折叠的 条评论
为什么被折叠?



