Shortest Path Algorithm

Dijkstra algo.

Mechanism

  1. Set start node
  2. Init shortest path table w/ INF
  3. Select shortest path node among unvisited nodes
  4. Calculate cost from selected node toward another node and set shortest path table.
  5. repeat 3, 4

Using heapq

import heapq

def heapsort(iterable):
    h = []
    result = []

    for v in iterable:
        heapq.heappush(h, value)

    for i in range(len(h)):
        result.append(heapq.heappop(h))
    return result

result = heapsort([1, 5, 2, 4, 3])
print(result)

src code: Dijkstra

Floyed-Warshall algo.

e.g.) a to b path through i:

D23 = min(D_23, D_2i + D_i3)
D24 = min(D_24, D_2i + D_i4)
D32 = min(D_32, D_3i + D_i2)
D34 = min(D_34, D_3i + D_i4)
D42 = min(D_42, D_4i + D_i2)
D43 = min(D_43, D_4i + D_i3)

src code: Floyed-Warshall

Bellman-Ford algo.

Condition:

  1. No cycle -> max V -1 edges
  2. Repeat until there’s no nodes to update min distance.
  3. If updating w/ infinite negative cost (negative cycle), escape loop

src code: Bellman-Ford

Traveling Salesman Problem (TSP)

Minimum Spanning Tree (MST)

Spanning tree: Partial graph that includes all nodes w/o cycle

  Graph Tree
Direction Directed/Undirected Directed
Cycle Cyclic/Acyclic Acyclic
Root node X O
nodal relation none parent/child
model network hierchy

Kruskal’s algo

Primm’s algo

DAG (Topological Sort)