06 Basic Graph Algorithms
06 Basic Graph Algorithms
06 Basic Graph Algorithms
Jaehyun Park
What are graphs? Adjacency Matrix and Adjacency List Special Graphs Depth-First Search and Breadth-First Search Topological Sort Eulerian Circuit Minimum Spanning Tree (MST) Strongly Connected Components (SCC)
An abstract way of representing connectivity using nodes (or vertices) and edges We will label the nodes from 1 to edges connect some pairs of nodes
Edges
path problems Network flow problems Matching problems 2-SAT problem Graph coloring problem Traveling Salesman Problem (TSP): still unsolved! and many more
Storing Graphs
We need to store both the set of nodes and the set of edges
Nodes
all edges incident to a particular node Testing if given two nodes are directly connected
Adjacency Matrix
time
Make an matrix
Uses 2 memory
use when is less than a few thousands, AND when the graph is dense
Only
Adjacency List
3
3 1 2 6 5 4 From Last Edge ID
3 4 5 6 7 8
2 7
contains the edges LE contains the starting pointers of the edge lists
E LE[i] = 0
Special Graphs
Special Graphs
Bipartite Graph
Nodes
can be separated into two groups and such that edges exist between and only (no edges within or within )
Graph Traversal
The most basic graph algorithm that visits nodes of a graph in certain order Used as a subroutine in many other algorithms
We will cover two algorithms
Depth-First
Search (DFS): uses recursion (stack) Breadth-First Search (BFS): uses queue
Use non-recursive version if recursion depth is too big (over a few thousands)
Replace
Topological Sort
Input: a DAG = , Output: an ordering of nodes such that for each edge , comes before There can be many answers
e.g.
{6, 1, 3, 2, 7, 4, 5, 8} and {1, 6, 2, 3, 4, 5, 7, 8} are valid orderings for the graph on the right
6
2 1 4 3
Topological Sort
Any node without an incoming edge can be the first element After deciding the first node, remove outgoing edges from it Repeat!
Time complexity: 2 +
Ugh,
too slow
Precompute the number of incoming edges deg for each node Put all nodes with zero deg into a queue Repeat until becomes empty:
from For each edge
Take
Time complexity: +
Eulerian Circuit
Given an undirected graph We want to find a sequence of nodes that visits every edge exactly once and comes back to the starting point Eulerian circuits exist if and only if
Pick any node in and walk randomly(!) without using the same edge more than once Each node is of even degree, so when you enter a node, there will be an unused edge you exit through
Except
the cycle and repeat the process in each connected component Glue the cycles together to finish!
Related Problems
Eulerian path: exists if and only if the graph is connected and the number of nodes with odd degree is 0 or 2.
Hamiltonian path/cycle: a path/cycle that visits every node in the graph exactly once. Looks similar but still unsolved!
Given an undirected weighted graph = , Want to find a subset of with the minimum total weight that connects all the nodes into a tree
We will cover two algorithms:
Kruskals
Kruskals Algorithm
Main idea: the edge with the smallest weight has to be in the MST
Simple
proof:
not. Take the MST that doesnt contain . to , which results in a cycle. Remove the edge with the highest weight from the cycle.
Assume Add
Kruskals Algorithm
Another main idea: after an edge is chosen, the two nodes at the ends can be merged and considered as a single node (supernode) Pseudocode:
Sort
the edges in increasing order of weight Repeat until there is one supernode left:
Take If
Otherwise,
Prims Algorithm
Main idea:
a set that starts out with a single node Find the smallest weighted edge = , that connects and Add to the MST, add to Repeat until =
Maintain
Differs from Kruskals in that we grow a single supernode instead of growing multiple ones here and there
Repeat until = :
Find
Add
with smallest
a priority queue or a simple linear search
Use
to min , cost ,
Can be modified to compute the actual MST along with the total weight
Kruskals vs Prims
Kruskals Algorithm
log time Pretty easy to code Generally slower than Prims
Takes
Prims Algorithm
Time A
Can
Given a directed graph = , A graph is strongly connected if all nodes are reachable from every single node in Strongly connected components of are maximal strongly connected subgraphs of
The
graph on the right has 3 SCCs: {a, b, e}, {c, d, h}, {f, g}
Figure from Wikipedia
Kosarajus Algorithm
Check the current node as visited Recurse on all unvisited neighbors After the DFS calls are finished, increment and set s label to
Reverse the direction of all the edges For node with label 1
Kosarajus Algorithm
We wont prove why this works Two graph traversals are performed
Running
time: +
Other SCC algorithms exist but this one is particularly easy to code
and
asymptotically optimal