Maktub_Wiki Maktub_Wiki
主站 (opens new window)
  • 服务搭建
  • 网络服务
  • 开源框架
  • 操作系统
  • iOS/MacOS
  • 算法导论(Python)
  • Leetcode
  • 线性代数
主站 (opens new window)
  • 服务搭建
  • 网络服务
  • 开源框架
  • 操作系统
  • iOS/MacOS
  • 算法导论(Python)
  • Leetcode
  • 线性代数
  • 数据结构

    • 树状数组
    • 位存储
    • 并查集
  • 算法

    • Floyd算法
    • Dijkstra算法
    • Bellman-Ford算法
      • Prim算法
      • Kruskal算法
      • KMP算法
    • Leetcode
    • 算法
    Maktub_小明
    2024-01-07
    目录

    Bellman-Ford算法

    # 说明

    从某个点出发,求最短路径算法, 可以有负权路径,带路径

    # 模版

    class Graph:
        def __init__(self, vertices):
            self.M = vertices   # Total number of vertices in the graph
            self.graph = []     # Array of edges
    
        # Add edges
        def add_edge(self, a, b, c):
            self.graph.append([a, b, c])
    
        def bellman_ford(self, src):
            distance = [float("Inf")] * self.M
            distance[src] = 0
            for i in range(self.M+1):
                for a, b, c in self.graph:
                    if distance[a] != float("Inf") and distance[a] + c < distance[b]:
                        if i == self.M:
                            # 出现环了,可以无限减少
                            return -1 
                        distance[b] = distance[a] + c
    
    上次更新: 2025/08/03, 09:26:17
    Dijkstra算法
    Prim算法

    ← Dijkstra算法 Prim算法→

    Theme by Vdoing | Copyright © 2021-2025 Maktub_小明 | MIT License
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式