




















Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





















Graph Implementation
Adjacency matrix
2D array of neighbors Adjacency list
List of neighbors Adjacency set / map
Set / map of neighbors
Affects efficiency / storage
Adjacency Matrix
Single array for entire graph Undirected graph
Only upper / lower triangle matrix needed Since n
, nj
k^
implies n
, nk
j
Unweighted graph
Matrix elements
boolean
Weighted graph
Matrix elements
weight
Adjacency List
For each node, store
List of neighbors / successors
Linked list Array list
For weighted graph
Also store weight for each edge Undirected graph
For every edge (a, b)
Nodes a & b need to store each other as neighbor
Directed graph
May also need to store list of predecessors
Adjacency Set / Map
For each node, store
Set or map of neighbors / successors For unweighted graph
Use set of neighbors For weighted graph
Use map of neighbors, w/ value = weight of edge Undirected graph
For every edge (a, b)
Nodes a & b need to store each other as neighbor
For directed graph
May also need to store map of predecessors
Graph Space Requirements
2
entries (for graph with N nodes, E edges)
Many empty entries for large, sparse graphs
2×E entries
2×E entries Space overhead per entry
Higher than for adjacency list
Graph Time Requirements
For graph with N nodes, E edges Operation
Adj Matrix
Adj List
Adj Set/Map
Find edge
Insert edge
Delete edge
Enumerate edges for node
Choosing Graph Implementations Graph density
Ratio edges to nodes (dense vs. sparse)
Neighbor based
For each node X in graph
For each neighbor Y of X // adj list faster if sparse
doWork( )
Connection based
For each node X in …
For each node Y in …
if (X,Y) is an edge
// adj matrix faster if dense
doWork( )
Shortest Path – Dijkstra’s Algorithm^ Maintain
Nodes with known shortest path from start
Cost of shortest path to node K from start
Only for paths through nodes in S Predecessor to K on shortest path
Updated whenever new (lower) C[K] discovered Remembers actual path with lowest cost
Shortest Path – Intuition for Dijkstra’s
Shortest pathsare known fornodes in S Store in C[K]length ofshortest path tonode K (for allpaths throughnodes in { S } ) Add to { S } nextclosest node
Shortest Path – Dijkstra’s Algorithm S =
P[ ] = none for all nodesC[start] = 0, C[ ] =
for all other nodes
while ( not all nodes in S
find node K not in S with smallest C[K]add K to Sfor each node J not in S adjacent to K
if ( C[K] + cost of (K,J) < C[J] )
C[J] = C[K] + cost of (K,J)P[J] = K
Dijkstra’s Shortest Path Example
none
none
none
none
none
Djikstra’s Shortest Path Example
none
1
1
none
none
Djikstra’s Shortest Path Example
none
1
1
none
none