Lecture 023
Graphs
Vertices: node (v)
Edge: lines (e=[0, v(v-1)/2])
Endpoints: at the end of edges
Un-directed: (A, B) = (B, A)
No Self-Edge: no (V, V)
Neighbors: vertices' connected to
Subgraph: a portion of the graph
Complete graph: every vertex connects

Lights Out

Possibilities
Board Configuration: 2^{n^2}
Possible Moves: n^2
Vertices: 2^{n^2}
Edges: n^2 * 2^{n^2} / 2

2^{n^2} vertices, each has n^2 neighbors, since un-directed, divide by 2.
Implicit graph: We don't need a graph data structure

Explicit graph: data structure in memory

Graph Interface

More Interface

iterate through neighbors of a vertex without repeating
Implementation
Vertices: node (v)
Edge: lines (e=[0, v(v-1)/2])
Neighbors: [0, min(v, e)]
Cost: e \in O(v^2) , but might be lower if we use e too.

Linked list of edges
Hash set of edges
Matrix
List
graph_hasedge
O(e)
O(1) avg+amt
O(1)
O(min(v,e))
graph_addedge
O(1)
O(1)
O(1)
O(1)
graph_get_neighbors
O(e)
O(e)
O(v)
O(1) cuz grab
space
O(v^2)
O(v+e)\O(max(v,e))

iterate neighbors: O(1)*O(min(v,e))
dense graph: e \in O(v^2)
sparse graph: e \in O(v) \lor e \in O(vlog(v)) (we typically work with sparse graphs)

Use Adjacency List

Representation

Adjacency Matrix

adjacency matrix mirrors

nothing in the middle

Adjacency List

Space

Code

Graph Type

Vertex

Representation Invariants

is_adj()

addedge

Simple Operations

graph_hasedge

Free

Next Neighbors

Define a struct

get_neighbors

next_neighbors

hasmore, free

printing
- Adjacency list costs O(v+e)

Here
- Adjacency matrix costs O(v^2)
- for dense graph they are the same, for sparse graph Adjacency list is better

Complexity Summary