广告位
468x60
正文内嵌广告1
¥500/月
课程简介
课程简介
本课程面向计算机科学初学者,系统讲解图算法基础。从图的基本概念入手,逐步深入图的表示方法、遍历算法(DFS、BFS)及最短路径算法(Dijkstra、Floyd-Warshall)。通过社交网络分析、路径规划等实战案例,帮助学员理解图算法的实际应用场景,提升解决复杂问题的能力。课程注重理论与实践结合,适合大学生、应届毕业生及职场新人学习。
后续扩展课程
课程大纲
第1章第一章 图的基本概念
- 1.1 图的定义与分类30min
- 1.2 图的表示方法(邻接矩阵、邻接表)45min
第2章第二章 图的遍历算法
- 2.1 深度优先搜索(DFS)45min
- 2.2 广度优先搜索(BFS)45min
- 2.3 DFS与BFS的应用案例60min
第3章第三章 最短路径算法
- 3.1 Dijkstra算法详解60min
- 3.2 Floyd-Warshall算法详解60min
- 3.3 最短路径算法的应用案例60min
广告位
336x280
正文内嵌广告2
¥700/月
课程资料
图算法基础:从入门到实战应用
第一章 图的基本概念
1.1 图的定义与分类
图(Graph)是由顶点(Vertex)和边(Edge)组成的非线性数据结构,用于表示对象及其相互关系。图可分为两大类:
- 无向图(Undirected Graph):边无方向,表示顶点间的双向关系
- 有向图(Directed Graph):边有方向,表示顶点间的单向关系
根据边的权重,图还可分为:
- 带权图(Weighted Graph):边带有权重值
- 无权图(Unweighted Graph):边无权重值
graph LR
A[顶点A] -- 无向边 --> B[顶点B]
C[顶点C] --> D[顶点D]
subgraph 带权图
E[顶点E] -- 权重5 --> F[顶点F]
end
1.2 图的表示方法(邻接矩阵、邻接表)
图的常用表示方法有两种:
邻接矩阵(Adjacency Matrix)
使用二维数组存储顶点间的关系,适合稠密图
# 无向图的邻接矩阵表示
class GraphMatrix:
def __init__(self, vertices):
self.vertices = vertices
self.matrix = [[0] * vertices for _ in range(vertices)]
def add_edge(self, u, v):
self.matrix[u][v] = 1
self.matrix[v][u] = 1 # 无向图需对称设置
# 示例:创建包含4个顶点的图
g = GraphMatrix(4)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
邻接表(Adjacency List)
使用链表或数组存储每个顶点的邻接顶点,适合稀疏图
# 图的邻接表表示
class GraphList:
def __init__(self, vertices):
self.vertices = vertices
self.adj_list = [[] for _ in range(vertices)]
def add_edge(self, u, v):
self.adj_list[u].append(v)
self.adj_list[v].append(u) # 无向图需双向添加
# 示例:创建包含4个顶点的图
g = GraphList(4)
g.add_edge(0, 1)
g.add_edge(0, 2)
g.add_edge(1, 3)
| 表示方法 | 空间复杂度 | 查找邻接顶点 | 适用场景 |
|---|---|---|---|
| 邻接矩阵 | O(V²) | O(1) | 稠密图 |
| 邻接表 | O(V+E) | O(degree(V)) | 稀疏图 |
本节小结
- 图由顶点和边组成,分为有向/无向、带权/无权
- 邻接矩阵适合稠密图,邻接表适合稀疏图
- 两种表示方法各有优劣,需根据实际场景选择
第二章 图的遍历算法
2.1 深度优先搜索(DFS)
深度优先搜索(Depth-First Search)是一种递归或栈实现的遍历算法,特点是一直深入到无法继续为止,然后回溯。
# DFS递归实现
def dfs_recursive(graph, vertex, visited=None):
if visited is None:
visited = set()
visited.add(vertex)
print(vertex, end=' ')
for neighbor in graph.adj_list[vertex]:
if neighbor not in visited:
dfs_recursive(graph, neighbor, visited)
# 示例使用
graph = GraphList(4)
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 3)
dfs_recursive(graph, 0) # 输出: 0 1 3 2
2.2 广度优先搜索(BFS)
广度优先搜索(Breadth-First Search)使用队列实现,特点是先访问离起始顶点最近的顶点。
from collections import deque
# BFS实现
def bfs(graph, start):
visited = set()
queue = deque([start])
visited.add(start)
while queue:
vertex = queue.popleft()
print(vertex, end=' ')
for neighbor in graph.adj_list[vertex]:
if neighbor not in visited:
visited.add(neighbor)
queue.append(neighbor)
# 示例使用
bfs(graph, 0) # 输出: 0 1 2 3
2.3 DFS与BFS的应用案例
社交网络好友推荐:使用BFS找到距离某用户最近的潜在好友
graph TD
A[用户A] --> B[好友B]
A --> C[好友C]
B --> D[好友D]
C --> E[好友E]
D --> F[好友F]
- 从用户A开始BFS遍历
- 第一层:B、C(直接好友)
- 第二层:D、E(好友的好友)
- 第三层:F(二级好友的好友)
- 推荐D、E作为潜在好友
迷宫最短路径:使用DFS寻找所有路径,BFS寻找最短路径
# 迷宫表示(0可通行,1障碍)
maze = [
[0, 1, 0, 0],
[0, 0, 0, 1],
[0, 1, 0, 0],
[0, 0, 1, 0]
]
# BFS寻找最短路径
def bfs_maze(maze, start, end):
rows, cols = len(maze), len(maze[0])
queue = deque([(start, [start])])
visited = set([start])
while queue:
(x, y), path = queue.popleft()
if (x, y) == end:
return path
for dx, dy in [(0,1),(1,0),(0,-1),(-1,0)]:
nx, ny = x + dx, y + dy
if 0<=nx<rows and 0<=ny<cols and maze[nx][ny]==0 and (nx,ny) not in visited:
visited.add((nx, ny))
queue.append(((nx, ny), path + [(nx, ny)]))
return None
print(bfs_maze(maze, (0,0), (3,3))) # 输出最短路径坐标列表
本节小结
- DFS适合寻找所有解,BFS适合寻找最短解
- 社交网络推荐常用BFS,迷宫求解可结合DFS和BFS
- 两种算法时间复杂度均为O(V+E)
第三章 最短路径算法
3.1 Dijkstra算法详解
Dijkstra算法用于解决带权有向图的单源最短路径问题,要求所有边权重非负。
import heapq
def dijkstra(graph, start):
# 初始化距离字典
distances = {vertex: float('infinity') for vertex in range(graph.vertices)}
distances[start] = 0
# 使用优先队列(最小堆)
heap = [(0, start)]
while heap:
current_distance, current_vertex = heapq.heappop(heap)
# 如果当前距离大于已记录距离,跳过
if current_distance > distances[current_vertex]:
continue
for neighbor, weight in enumerate(graph.matrix[current_vertex]):
if weight > 0: # 有边存在
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(heap, (distance, neighbor))
return distances
# 带权图的邻接矩阵表示
class WeightedGraphMatrix:
def __init__(self, vertices):
self.vertices = vertices
self.matrix = [[0] * vertices for _ in range(vertices)]
def add_edge(self, u, v, weight):
self.matrix[u][v] = weight
# 示例使用
wg = WeightedGraphMatrix(4)
wg.add_edge(0, 1, 4)
wg.add_edge(0, 2, 1)
wg.add_edge(1, 3, 1)
wg.add_edge(2, 1, 2)
wg.add_edge(2, 3, 5)
print(dijkstra(wg, 0)) # 输出: {0: 0, 1: 3, 2: 1, 3: 4}
3.2 Floyd-Warshall算法详解
Floyd-Warshall算法用于解决所有顶点对之间的最短路径问题,允许边权重为负(但不能有负权环)。
def floyd_warshall(graph):
# 初始化距离矩阵
dist = [[float('infinity')] * graph.vertices for _ in range(graph.vertices)]
for i in range(graph.vertices):
dist[i][i] = 0
for u in range(graph.vertices):
for v in range(graph.vertices):
if graph.matrix[u][v] > 0:
dist[u][v] = graph.matrix[u][v]
# 动态规划更新距离
for k in range(graph.vertices):
for i in range(graph.vertices):
for j in range(graph.vertices):
if dist[i][j] > dist[i][k] + dist[k][j]:
dist[i][j] = dist[i][k] + dist[k][j]
return dist
# 示例使用
print(floyd_warshall(wg))
# 输出: [[0, 3, 1, 4], [inf, 0, inf, 1], [inf, 2, 0, 3], [inf, inf, inf, 0]]
3.3 最短路径算法的应用案例
城市交通导航:使用Dijkstra算法计算两点间最短行车路线
graph TD
A[城市A] --10km--> B[城市B]
A --15km--> C[城市C]
B --5km--> D[城市D]
C --12km--> D
B --20km--> E[城市E]
D --8km--> E
- 从城市A出发,使用Dijkstra算法计算到各城市最短距离
- 结果:A→B(10km), A→D(15km via B), A→E(23km via B)
航班最优中转:使用Floyd-Warshall算法计算所有城市间最短飞行时间
# 航班图表示(城市0-3,飞行时间分钟)
air_graph = WeightedGraphMatrix(4)
air_graph.add_edge(0, 1, 120)
air_graph.add_edge(0, 2, 180)
air_graph.add_edge(1, 2, 90)
air_graph.add_edge(1, 3, 150)
air_graph.add_edge(2, 3, 120)
# 计算所有城市对最短飞行时间
all_pairs = floyd_warshall(air_graph)
for i in range(4):
for j in range(4):
if all_pairs[i][j] != float('infinity'):
print(f"城市{i}到城市{j}最短飞行时间: {all_pairs[i][j]}分钟")
本节小结
- Dijkstra适合单源最短路径,Floyd-Warshall适合所有顶点对
- Dijkstra不能处理负权边,Floyd-Warshall可以但需检测负权环
- 实际应用中需根据数据规模和需求选择合适算法
通过本课程的学习,学员已掌握图的基本概念、表示方法及经典遍历和最短路径算法。这些知识是解决社交网络分析、路径规划、网络路由等实际问题的基础,建议通过推荐实验进一步巩固所学内容。
广告位
300x250
正文内嵌广告3
¥600/月