






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 j , n k implies n k , n j Unweighted graph Matrix elements boolean Weighted graph Matrix elements weight
Adjacency List/Set
For each node, store List/Set of neighbors / successors Linked list Array list For weighted graph Also store weight for each edge Using a Map is a good choice For undirected graph with edge (a ↔ b) Nodes a & b need to store each other as neighbor For directed graph with edge (a → b) Node a needs to store node b as neighbor
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 For undirected graph with edge (a ↔ b) Nodes a & b need to store each other as neighbor For directed graph with edge (a → b) Node a needs to store node b as neighbor
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 O(1) O(E/N) O(1) Insert edge O(1) O(E/N) O(1) Delete edge O(1) O(E/N) O(1) Enumerate edges for node
Choosing Graph Implementations
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( )