Core Graph Algorithms Pseudocode Reference
Classified in Computers
Written on in
English with a size of 3.58 KB
Core Graph Algorithms Pseudocode
Kruskal's Algorithm for MST
def Kruskal(V, E):
- Sort E by increasing weight.
- For each vertex v in V: create a tree for each v.
MST = {}
For i from 1 to |E|:
- (u, v) ← lightest edge in E.
- If u and v are not in the same tree:
MST.add((u,v))- Merge u and v trees.
Return MST.
Huffman Tree Construction
BuildHuffman(characters[1..n], frequencies[1..n]):
- Create nodes for each character.
- For i ← 1 to n: create a min-heap Q with each node frequency as a key.
While(length(Q) > 1):
- x = pop minimum value from Q.
- y = pop minimum value from Q.
- Create new node z.
z.key = x.key + y.keyz.leftChild = xz.rightChild = y- Insert z into Q.
Return the root value from Q.
Topological Sort
topological_sort(G):
Stack = []
While (unvisited Nodes):
helper_toposort(currentNode in G):
- Mark
currentNodeas visited.- For node in
currentNode.neighbours:
- If (node is not already visited):
helper_toposort(node).Stack.insert(currentNode).
Return Result in reverse order.
Dijkstra's Shortest Path Algorithm
def Dijkstra(G, s):
- # Add nodes to min-priority queue Q with initial distance infinity.
- For v in V:
Enqueue(Q, v, 'infinity'). - # In Q, make source priority = 0.
DecreaseKey(Q, source, 0).
visited = []
While(length(Q) > 0):
currentNode = Dequeue(Q)# Pick and delete the min distance node.visited.append(currentNode).- For v in
currentNode.neighbours:
- If (v not in visited):
dist_V = min{dist_V, weight(currentNode, v) + dist_currentNode}.DecreaseKey(Q, v, dist_V).
Prim's Algorithm for MST
def prims(G):
- s ← pick a source vertex from V.
- For v in V: # v: current vertex; V: all the vertices in G.
dist[v] = infinityprev[v] = Empty
dist[s] = 0prev[s] = Empty/None
dist[node] = weight of (s, node)prev[node] = s
CurrentNode = unvisited vertex v with smallest dist[v].MST.add((prevNode, CurrentNode)).- For node in
CurrentNode.neighbours:dist[node] = min(w(CurrentNode, node), dist[node]).- If
dist[node]updated:prev[node] = CurrentNode.
visited.add(CurrentNode).
Return MST.