Dijkstra's Algorithm and Tries

Breadth-first Search

  • Breadth-first Search (BFS): An algorithm for visiting all nodes explorable from a given starting node.

    • Precondition: The starting node must be unvisited.
    • Utilizes a queue to maintain the order of nodes to be visited.
    • Invariant: All nodes to be visited are explorable from some node in the queue.
  • BFS Algorithm: Given a node ID:

    1. Create a queue and enqueue the starting node ID.
    2. While the queue is not empty:
      • Dequeue a node uu from the queue.
      • If uu has not been visited:
        • Visit uu.
        • For each edge (u,v)(u, v) from uu, enqueue vv into the queue.

Dijkstra's Algorithm

Weighted Graphs

  • Definition: A graph (V,E)(V, E) where edges have associated weights, represented by a weight function.
  • Graphs can be directed or undirected.
  • Representation:
    • Adjacency List: Store the weight of the edge (u,v)(u, v) along with node vv in uu's list.
    • Adjacency Matrix: Store the weight in the matrix entry corresponding to (u,v)(u, v).

Paths in Weighted Graphs

  • The length (or weight) of a path in a weighted graph is the sum of the weights of the edges in that path.
  • Example: A path (1,6,4)(1, 6, 4) with edge weights 3 and 4, respectively, has a total weight of 3+4=73 + 4 = 7.

Computing Shortest Paths

  • Unweighted Graphs: Breadth-first search (BFS) can be used. BFS visits nodes in order of hop distance or path length.
    Example: BFS(1) visits nodes at hop distances 0, 1, 1, 2, 2, 3
  • Weighted Graphs: BFS does not guarantee visiting nodes in order of shortest path length due to varying edge weights.

Dijkstra’s Shortest Paths: Subpaths

  • Fact: Subpaths of shortest paths are also shortest paths.
  • Example: If the shortest path from uu to ww goes through vv, then the path from uu to vv is the shortest path from uu to vv.
  • Consequence: A candidate shortest path from a start node ss to a neighbor ww of vv is the shortest path from ss to vv plus the weight of the edge from vv to ww.
    • v.dv.d: shortest known distance from the start node ss to vv.
    • wt(v,w)wt(v, w): the weight of the edge from vv to ww.

Dijkstra’s Shortest Paths: Intuition

  • Explore nodes in order of path length, similar to BFS but considering edge weights.
  • Node Categories:
    • Settled: Nodes for which the actual shortest path is known.
    • Frontier: Visited nodes for which the shortest path is not yet finalized.
    • Unexplored: All other nodes.
  • Each node nn maintains n.dn.d, the length of the shortest known path from the start node.
  • Shorter paths to frontier nodes may be discovered, updating n.dn.d accordingly.

Dijkstra’s Shortest Paths: High-Level Algorithm

  1. Initialization:
    • Settled set is empty.
    • Frontier set contains only the start node.
  2. Iteration: While the frontier is not empty:
    • Move the node ff with the smallest dd value from the frontier to the settled set.
    • For each neighbor ww of ff:
      • If ww has not been seen before:
        • Set its path length (w.d) to f.d + weight(f,w)
        • Add it to the frontier.
      • Else, if the path to ww via ff is shorter than its current shortest path length:
        • Update ww's shortest path length to f.d+wt(f,w)f.d + wt(f, w).

Dijkstra’s Shortest Paths: Execution Example

  • Demonstrates the execution of Dijkstra’s algorithm on a sample graph.
  • The values are iteratively updated in each node
  • The shortest path is computed from node 4.

Dijkstra’s Shortest Paths: Pseudocode

S = { };
F = {v};  // v is the starting node
v.d = 0;  // Distance from v to itself is 0

while (F ≠ {}) {
    f = node in F with min d value;  // Node with smallest known distance
    Remove f from F, add it to S;      // Move node from Frontier to Settled

    for each neighbor w of f {
        if (w not in S or F) {          // If neighbor w is Unexplored
            w.d = f.d + weight(f, w);  // Update shortest distance to w
            add w to F;                  // Add w to Frontier
        } else if (f.d + weight(f, w) < w.d) {
            w.d = f.d + weight(f, w);  // Update shortest distance to w if shorter path found
        }
    }
}

At termination: for each reachable node n, n.d stores the length of the shortest path from v to n.

Shortest path backpointer

To reconstruct the shortest path, maintain a backpointer at each node pointing to the previous node in the shortest path. Add the following lines to the pseudocode:

v.bp = null;  // Initialize backpointer of start node to null
...
if (w not in S or F) {
    w.d = f.d + weight(f, w);
    w.bp = f;       // Set backpointer of w to f
    add w to F;
} else if (f.d + weight(f, w) < w.d) {
    w.d = f.d + weight(f, w);
    w.bp = f;       // Update backpointer of w to f
}
  • Example: To find the shortest path to Node 3, traverse backpointers: 3 -> 2 -> 0 -> 4

Implementing Dijkstra Efficiently

  1. Store Frontier in a min-heap priority queue with dd-values as priorities.
  2. Use an adjacency list graph representation for efficient neighbor iteration.
  3. Use a HashMap
  4. Do not explicitly store Settled or Unexplored sets: a node is in SS or FF iff it is in the map.

Tries

Trie Introduction and Definitions

  • Trie: Pronounced "try" or "tree", also called digital tree or prefix tree.
  • Alternative to BSTs for implementing the Set ADT and Map ADT.
  • Keys are a sequence of symbols/characters/digits from some alphabet.
    • Example: Keys are W-numbers, alphabet = {0,1,2,…,9,W}\lbrace 0, 1, 2, …, 9, W\rbrace
    • Example: Keys are English words without punctuation, alphabet = {a,b,…,z,A,B,…,Z}\lbrace a, b, …, z, A, B, …, Z\rbrace
  • Tree data structure that uses position rather than comparisons
  • Commonly used in predictive text or autocomplete dictionaries.

TrieNode Definition

Example

class TrieNode<S,V> {
    HashMap<S,TrieNode> children; // S is symbol type; e.g., Character
    boolean terminates;            // for implementing Set ADT (checkmark)
    V value;                     // This variable stores additional information associated with the node, e.g. frequency.
}
  • children: Maps symbols to child TrieNodes.
  • terminates: Indicates if this node represents the end of a valid key (for Set ADT).
  • value: Stores additional information associated with the node (e.g., frequency).

Trie Search

  • Algorithm: contains(T, key)
    1. If T is null: return false (for Set) or null (for Map)
    2. If key is an empty string: return T.terminates (for Set) or T.value (for Map)
    3. Otherwise: return contains(T.children.get(key[0]), rest(key))

Trie Insertion

Algorithm: Insert(Trie, key)

current = Trie.root
For Each character in key
    Search (Trie, key.character)
    If current does not have a child node for this character
        Create a new node
        Add the new node as a child of current, with the character as its label
    Move current to the child node corresponding to the current character
Mark the last node (current) as a leaf node or set a flag to indicate the end of a key

Trie Deletion

  • Algorithm: Delete(Trie, key)
    1. Search (Trie, key)
    2. If not found: Return.
    3. Else: Set terminates to false (for Set) or value to null (for Map).
  • Using lazy deletion where it's toggling a flag rather than freeing memory

Trie Runtime

  • Contains: O(Lkey) *Lkey is the length of a key, which is usually constant O(1).
  • With a max key length, worst-case time complexities:
    • Contains: O(1)
    • Insert: O(1)
    • Delete: O(1)

Critical Thinking

  • Tries and radix sort can be good options when the keys are convenient and naturally bounded.
  • They are not magic bullets.
  • "Constant" time can be a big "constant".
  • Asymptotic analysis doesn’t tell the full story.