Graphs

C++ Reading: Chapter 13 of Goodrich
Java Reading: Chapter 14 of Goodrich

A graph \(G\) is a collection \(V\) of vertices with a collection \(E\) of vertex pairs known as edges. Here collection is used instead of set to admit multiples.

Graph Terminology

Let \(n\) be the number of nodes and \(m\) be the number of edges.

\[\sum_{v\ \textrm{in}\ G} \textit{deg}(v) = 2m\]

\[\sum_{v\ \textrm{in}\ G} \textit{indeg}(v) = \sum_{v\ \textrm{in}\ G} \textit{outdeg}(v) = m\]

A simple graph has \(O(n^2)\) edges.

If \(G\) is an undirected and connected then \(m \ge n - 1\).

If \(G\) is an undirected tree then \(m = n - 1\).

If \(G\) is an undirected forest then \(m \le n - 1\).

Basic Graph ADT Operations

A graph ADT allows data to be stored at all vertices and all edges of a graph.

Operations on graphs

 vertices()
 edges()
 insertVertex(x)
 insertEdge(u, v, a)
 eraseVertex(v)
 eraseEdge(e)

Operations on vertices

 incidentEdges(v)
 isAdjacentTo(u, v)

Operations on edges

 endVertices(e)
 opposite(e, v)
 isIncidentOn(e, v)

Graph Representations

Operation Edge List Adjacency List Matrix
vertices \(O(n)\) \(O(n)\) \(O(n)\)
edges \(O(m)\) \(O(m)\) \(O(n^2)\)
endVertices \(O(1)\) \(O(1)\) \(O(1)\)
opposite \(O(1)\) \(O(1)\) \(O(1)\)
incidentEdges \(O(m)\) \(O(\deg(v))\) \(O(n)\)
isAdjacentTo \(O(m)\) \(O(\min(\deg(v),\deg(w)))\) \(O(1)\)
isIncidentOn \(O(1)\) \(O(1)\) \(O(1)\)
insertVertex \(O(1)\) \(O(1)\) \(O(n^2)\)
insertEdge \(O(1)\) \(O(1)\) \(O(1)\)
eraseVertex \(O(m)\) \(O(\deg(v))\) \(O(n^2)\)
eraseEdge \(O(1)\) \(O(1)\) \(O(1)\)

Traversal

Traversal is \(O(n + m)\)

  traverse(\(s\))
   mark all nodes as unvisited
   \(C\).insert(\(s\))
   while \(C\) is not empty
    \(v \gets C\).remove()
    mark \(v\) visited
    for each \(w\) adjacent to \(v\)
     if \(w\) is not visited
      \(C\).insert(\(w\))

Weighted Graphs

Each edge has a weight. The length of a path is the sum of the edge weights along it. The distance from vertices \(u\) and \(v\) is the length of the shortest path from \(u\) to \(v\). The shortest path is no longer so simple.