Mathematically, a graph G is defined by a set V of vertices and a set E of edges. We write G=(V,E).

- V can be a set of anything (e.g. V={ my dog Tika, my cat Mittens, Mr. Ed the talking horse }).
- E must be a subset of the set { {u,v} : u,v ∈ V } (the unordered pairs of vertices in V).

If the graph is directed, then the edges are *ordered* pairs of vertices.
That is edge (u,v) is different than edge (v,u).

For example, the set of out-neighbors of a vertex w in a directed graph G=(V,E) can be expressed as {u ∈ V : (w,u) ∈ E } .

The digraph G=(V,E) where V={1,2,3,4} and E={(1,2), (1,3), (2,4), (3,4)} can be represented in a file as:

1: 2 3 2: 4 3: 4 4:

Or possibly as

1 2 3 4

1 2 1 3 2 4 3 4

**Adjacency list representation:**

- An array of vertices, where the ith vertex is stored at the ith position of the array. With the ith vertex we also store a doubly linked list of the neighbors of the vertex.

- Takes O(n+m) space, operations involving a vertex w typically take O(degree(w)) time.

**Adjacency matrix representation:**

- An n by n matrix M of boolean values, where M[i,j] is true if there is an edge from the ith vertex to the jth vertex.

- Takes O(n
^{2}) space. Finding all neighbors of a vertex takes Θ(n) time. Checking existence of an edge takes O(1) time.

**Hash table of Hash tables:**

- A hash table of vertices, each vertex is stored by ID (an integer counter) or some other hashable key (such as a string). With each vertex W, the neighbors of W are stored in another hash table. (So the data structure is a hash table of hash tables.)

- Takes O(n+m) space, most operations are constant time or take time proportional to the degree of the vertex involved.

For a concrete example of a Graph and Digraph class in C++, see program assignment 2 at ClassS04CS141/Prog2 and ClassS04CS141/Prog2Soln .

- GoodrichAndTomassia sections 6.1 and 6.2.
- ClassS04CS141/Prog2 and ClassS04CS141/Prog2Soln