Graphs Flashcards
Directed Edges
An edge (u,v) is from u to v, not v to u
Undirected Edges
An edge (u,v) is from u to v AND from v to u
Weighted Edges
Each edge has a “weight” (“cost”) associated with it (i.e. magnitude associated with relationship)
Unweighted Edges
Edges do not have weights
Cycle
A valid path starting and ending at the same node
Class: Unstructured
A disconnected collection of nodes
Class: Sequential
An ordered collection of connected nodes (i.e. Linked List)
Class: Hierarchical
A ranked collection of connected nodes
Class: Structured
A collection of both connected and disconnected nodes
Multigraph
A given pair of nodes may have multiple distinct edges (i.e. cites and flights, different prices between same cities)
Adjacency Matrix
O(|V|^2) Good for dense graphs. Not good for sparse graph. Must iterate through all indices Access constant time for searching.
From is rows, To is columns.
For undirected graph, it will be symmetric matrix.
Diagonals will be self directed path.
Adjacency List
Hash tables or has maps, or linked list. Has very fast look up and saves space without reference null connections unlike matrix. O(|V| + |E|)
Breadth First Search (BFS) Algorithm
- Add (0, start) to queue
- While the queue is not empty:
a. pop (d, curr) from the queue
b. if curr has not been visited:- mark curr as visited with distance d
- for all edges (curr, w):
if w has not been visited add (d+1, w) to queue
Depth First Search (DFS) Algorithm
- Add start to stack
- While the stack is not empty:
a. pop curr from stack
b. if curr has not been visited- mark curr as visited
- for all edges (curr, w):
- if w has not been visited, add w to stack
Dijkstra’s Algorithm
1. know prerequisite condition)
2. valid by proof by contradiction. No future path will be less than the current path using algorithms
3. keep track of the shortest path coming from
4.
Fundamentally the same as BFS (Queue and DFS (stack), but Dijkstra’s is a (min) heap where lowest distance is highest priority
Set all nodes to infinite distance. 1. add (0,start-inital node/source) to PQ/heap. Set others to -1 or infinity 2. while PQ !=empty: - A. Pop the (d,curr) from PQ - B. if curr is not done: - 1. mark curr as done - 2. (curr, w, e): only works for graphs with positive edge weights. No negative weights
Dijkstra’s Algorithm Time Complexity
Overall: O(|V| + |E| log |E|) P. Initialization of infinity = O(|V|) 1. Add (0,Start) to PQ = O(1) 2. while PQ not empty: A. Pop (d, curr) from PQ = O(log |E|) , since using a heap (perfectly balanced) number of pops is log of the number of edges