图结构与图算法:Python 深度剖析

196 阅读3分钟

图结构与图算法:Python 深度剖析 🚀


🔗 「1. 图的基础:如何在 Python 中表示和遍历图?」

「图(Graph)」 是一种更加灵活的数据结构,由顶点(Vertex)「和」**边(Edge)**组成,可以用来表示社交网络、地图、任务调度等场景。

「图的表示方法」

  • 「邻接矩阵」:使用二维数组存储图的连接关系
  • 「邻接表」:使用字典存储每个顶点及其相邻顶点,更节省空间

「代码示例:邻接表的实现」

class Graph:
    def __init__(self):
        self.graph = {}

    def add_edge(self, u, v):
        if u not in self.graph:
            self.graph[u] = []
        self.graph[u].append(v)

    def display(self):
        for node in self.graph:
            print(f"{node} -> {self.graph[node]}")

# 示例:构建一个简单图
g = Graph()
g.add_edge(01)
g.add_edge(02)
g.add_edge(12)
g.add_edge(20)
g.add_edge(23)
g.add_edge(33)

g.display()

「输出结果」

0 -> [1, 2]
1 -> [2]
2 -> [0, 3]
3 -> [3]

🔍 「2. 深度优先搜索(DFS):图遍历算法详解」

「深度优先搜索(DFS)」 是一种沿着一个分支探索到尽头,再回溯继续探索其他分支的图遍历算法。

「DFS 递归实现」

def dfs(graph, node, visited=None):
    if visited is None:
        visited = set()
    if node not in visited:
        print(node, end=" ")
        visited.add(node)
        for neighbor in graph[node]:
            dfs(graph, neighbor, visited)

# 示例:DFS 遍历
graph = {
    0: [12],
    1: [2],
    2: [03],
    3: [3]
}

dfs(graph, 0)  # 输出: 0 1 2 3

🌐 「3. 广度优先搜索(BFS):从层次遍历图结构的经典算法」

「广度优先搜索(BFS)」 是一种层次遍历算法,类似于树的层次遍历。

「BFS 代码实现」

from collections import deque

def bfs(graph, start):
    visited = set()
    queue = deque([start])
    visited.add(start)
    
    while queue:
        node = queue.popleft()
        print(node, end=" ")
        for neighbor in graph[node]:
            if neighbor not in visited:
                queue.append(neighbor)
                visited.add(neighbor)

# 示例:BFS 遍历
bfs(graph, 0)  # 输出: 0 1 2 3

🚀 「4. Dijkstra 算法:如何在图中寻找最短路径?」

「Dijkstra 算法」 是一种贪心算法,广泛用于计算**「加权图」**中从起点到所有其他节点的最短路径。

「代码实现」

import heapq

def dijkstra(graph, start):
    min_heap = [(0, start)]
    distances = {node: float('inf'for node in graph}
    distances[start] = 0

    while min_heap:
        current_distance, current_node = heapq.heappop(min_heap)
        
        if current_distance > distances[current_node]:
            continue
        
        for neighbor, weight in graph[current_node]:
            distance = current_distance + weight
            if distance < distances[neighbor]:
                distances[neighbor] = distance
                heapq.heappush(min_heap, (distance, neighbor))
    
    return distances

# 示例:加权图
graph = {
    0: [(14), (21)],
    1: [(31)],
    2: [(12), (35)],
    3: []
}

print(dijkstra(graph, 0))  # 输出: {0: 0, 1: 3, 2: 1, 3: 4}

🌲 「5. 最小生成树:Kruskal 与 Prim 算法的实现与比较」

「最小生成树(MST)」 是一种覆盖所有顶点且总权重最小的树,常用于网络设计和优化。

  • 「Kruskal 算法」:通过排序边并逐步添加到生成树中,避免形成环
  • 「Prim 算法」:从一个顶点开始,逐步扩展最小边

「Prim 算法示例」

import heapq

def prim(graph, start):
    min_heap = [(0, start)]
    visited = set()
    total_cost = 0
    
    while min_heap:
        cost, node = heapq.heappop(min_heap)
        if node not in visited:
            visited.add(node)
            total_cost += cost
            for neighbor, weight in graph[node]:
                if neighbor not in visited:
                    heapq.heappush(min_heap, (weight, neighbor))
    
    return total_cost

# 示例:加权图
graph = {
    0: [(14), (21)],
    1: [(04), (22), (31)],
    2: [(01), (12), (35)],
    3: [(11), (25)]
}

print(prim(graph, 0))  # 输出: 最小生成树的总权重

📌 「总结」

  • 「图结构」 是解决复杂关系问题的重要工具,遍历算法如 DFS 和 BFS 是理解图的关键。
  • 「Dijkstra 和最小生成树算法」 帮助我们在加权图中寻找最优解。

欢迎点赞 + 收藏,持续关注更多 Python 「编程纵深」的精彩内容! ❤️