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:
- Create a queue and enqueue the starting node ID.
- While the queue is not empty:
- Dequeue a node from the queue.
- If has not been visited:
- Visit .
- For each edge from , enqueue into the queue.
Dijkstra's Algorithm
Weighted Graphs
- Definition: A graph 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 along with node in 's list.
- Adjacency Matrix: Store the weight in the matrix entry corresponding to .
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 with edge weights 3 and 4, respectively, has a total weight of .
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 to goes through , then the path from to is the shortest path from to .
- Consequence: A candidate shortest path from a start node to a neighbor of is the shortest path from to plus the weight of the edge from to .
- : shortest known distance from the start node to .
- : the weight of the edge from to .
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 maintains , the length of the shortest known path from the start node.
- Shorter paths to frontier nodes may be discovered, updating accordingly.
Dijkstra’s Shortest Paths: High-Level Algorithm
- Initialization:
- Settled set is empty.
- Frontier set contains only the start node.
- Iteration: While the frontier is not empty:
- Move the node with the smallest value from the frontier to the settled set.
- For each neighbor of :
- If 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 via is shorter than its current shortest path length:
- Update 's shortest path length to .
- If has not been seen before:
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
- Store Frontier in a min-heap priority queue with -values as priorities.
- Use an adjacency list graph representation for efficient neighbor iteration.
- Use a HashMap
- Do not explicitly store Settled or Unexplored sets: a node is in or 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 =
- Example: Keys are English words without punctuation, alphabet =
- 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)- If
Tis null: returnfalse(for Set) ornull(for Map) - If
keyis an empty string: returnT.terminates(for Set) orT.value(for Map) - Otherwise: return
contains(T.children.get(key[0]), rest(key))
- If
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)
- Search (Trie, key)
- If not found: Return.
- 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.