ZiliangZiliang

Site navigation

  • Mortgage comparison
  • Japan tax calculator
  • Programming
  • Algorithms
  • Machine learning
  • Misc
Engineering
Contact
中文

Site navigation

  • Mortgage comparison
  • Japan tax calculator
  • Programming
  • Algorithms
  • Machine learning
  • Misc
Engineering
Contact

Article directory

  • Programming Languages

    • Overview
    • Basics
    • Collections
    • Flow Control Statements
    • Function
    • Libraries and Modules
    • IO, File, and OS
    • Errors and Exceptions
    • Object-Oriented Design
    • Namespaces and Scopes
  • Data Structures and Algorithms

    • Overview
    • Math Formula
    • Math Code
    • Misc
    • String
    • Tree Traversal
    • Balanced Binary Trees
    • Heap
    • Segment Tree
    • Dynamic Programming
    • Tree Misc
    • Java
    • Disjoint Sets
    • Graph Traversal
    • Minimum Spanning Tree
    • Single-Source Shortest Paths
    • Strongly Connected Components
    • Cut Vertices and Bridges
    • Cache
    • Binary Search
    • Quicksort
    • Knapsack Problem
    • Vertex Cover Problem
    • Set Cover Problem
    • Principle Component Analysis
    • K-Center Problem

Single-Source Shortest Paths

Example

Graph

Adjacency Matrix

0123456
00130000
11015000
23100100
30500200
40012040
50000402
60000020

Dijkstra's Algorithm

Require non-negative weights

Time Complexity: O((|E|+|V|)log⁡|V|) (use heap or priority queue) or O(|E|+|V|log⁡|V|) (use Fibonacci heap min-priority queue)

python
from heapq import heappop, heappush

def dijkstra(matrix, source) -> dict:
    # optimized by heap
    h = [(0, source)]
    visited = {}
    while h and len(visited) < len(matrix):
        weight, cur = heappop(h)
        if cur in visited:
            continue
        visited[cur] = weight
        for i, w in enumerate(matrix[cur]):
            if w > 0 and i not in visited:
                heappush(h, (weight + w, i))
    return visited

java
Map<Integer, Integer> dijkstra(int[][] matrix, int source) {
    int n = matrix.length;
    // PriorityQueue<int[]> pq = new PriorityQueue<>((a, b) -> a[0] - b[0]);
    PriorityQueue<Entry> pq = new PriorityQueue<>();
    pq.add(new Entry(0, source));
    Map<Integer, Integer> visited = new HashMap<>();
    while (!pq.isEmpty() && visited.size() < n) {
        Entry e = pq.poll();
        if (visited.containsKey(e.number)) {
            continue;
        }
        visited.put(e.number, e.distance);
        for (int i = 0; i < n; i++) {
            int w = matrix[e.number][i];
            if (w > 0 && !visited.containsKey(i)) {
                pq.add(new Entry(e.distance + w, i));
            }
        }
    }

    return visited;
}

Tests

python

java

Edit this page on GitHub
Last Updated: 9/10/26, 7:37 AM
Contributors: Lucien
Prev
Minimum Spanning Tree
Next
Strongly Connected Components