458 字
2 分钟
代码随想录算法训练营第四十三天 | 图论 Part01

图论基础#

  • 图论是计算机科学中重要的研究领域,广泛应用于网络、社交媒体、交通等领域。
  • 图由顶点(节点)和边(连接顶点的线段)组成。
  • 图可以是有向图(边有方向)或无向图(边无方向)。
  • 图的表示方法包括邻接矩阵、邻接表等。
  • 图的基本操作包括遍历(深度优先搜索 DFS、广度优先搜索 BFS)、最短路径计算、最小生成树等。

深度优先搜索理论#

  • 深度优先搜索(DFS)是一种遍历图的算法,从起始节点开始,尽可能深地搜索每个分支。
  • DFS 可以使用递归或栈实现。
  • 时间复杂度为 O(V+E)O(V + E),其中 VV 是顶点数,EE 是边数。
  • DFS 的应用包括拓扑排序、连通分量检测等。
def dfs(graph, start, visited=None):
if visited is None:
visited = set()
visited.add(start)
for neighbor in graph[start]:
if neighbor not in visited:
dfs(graph, neighbor, visited)
return visited

广度优先搜索理论#

  • 广度优先搜索(BFS)是一种遍历图的算法,从起始节点开始,先访问所有邻接节点,再逐层向外扩展。
  • BFS 使用队列实现。
  • 时间复杂度同样为 $O(V + E)$。
  • BFS 的应用包括最短路径计算、连通分量检测等。
from collections import deque
def bfs(graph, start):
visited = set()
queue = deque([start])
while queue:
node = queue.popleft()
if node not in visited:
print("Visiting:", node)
visited.add(node)
for neighbor in graph.get(node, []):
if neighbor not in visited:
queue.append(neighbor)
return visited

卡码网:98. 所有可达路径#

题目链接

import sys
input = sys.stdin.read
def main():
data = input().split()
n, m = int(data[0]), int(data[1])
graph = [[] for _ in range(n + 1)]
index = 2
for _ in range(m):
u = int(data[index])
v = int(data[index + 1])
graph[u].append(v)
index += 2
res = []
path = []
def dfs(node):
path.append(node)
if node == n:
res.append(path[:])
else:
for neighbor in graph[node]:
dfs(neighbor)
path.pop()
dfs(1)
if not res:
print(-1)
else:
for p in res:
print(' '.join(map(str, p)))
if __name__ == "__main__":
main()
代码随想录算法训练营第四十三天 | 图论 Part01
https://fuwari.vercel.app/posts/code_musings_day_forty-three/
作者
Jarrett
发布于
2025-07-30
许可协议
CC BY-NC-SA 4.0