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

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

Implicit graph: We don't need a graph data structure

Explicit graph: data structure in memory

Graph Interface

Graph Interface

More Interface

More Interface

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

Use Adjacency List

Representation

Adjacency Matrix

Adjacency Matrix

Code

Graph Type

Graph Type

Vertex

Vertex

Representation Invariants

Representation Invariants

is_adj()

is_adj()

addedge

addedge

Simple Operations

Simple Operations

graph_hasedge

graph_hasedge

Free

Free

Next Neighbors

Define a struct

Define a struct

get_neighbors

get_neighbors

next_neighbors

next_neighbors

hasmore, free

hasmore, free

printing

printing
- Adjacency list costs O(v+e)

Here

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

Complexity Summary

Complexity Summary

Table of Content