Graphs (1)
Formally, a graph G consists of a set V whose members are the vertices (nodes) of G, together with a set E of pairs of vertices from V. These pairs are called edges (or arcs, links) of G.
The size of each graph is measured by |V| and |E|, where 0 ≤ |V|, 0 ≤ |E| ≤ |V2|.
Linear and tree data structures are special cases of graph.
For example, we can have G = < V, E >, where V = {1, 2, 3, 4, 5} and E = {(1, 2), (2, 3), (3, 4), (4, 5), (1, 5), (3, 5), (2, 4)}. The graph looks like:
1---2---3
\ \ /|
\ X |
\ / \|
5---4
Please note that the same graph can be drawn in many ways.
Based on the edges, we can further define the following notions:
Then we can talk about connectivity:
A weighted graph has a number attached to each edge, to represent some kind of "distance". In such a graph, the weight of a path can be defined as the sum of the weights on the path.
Example: vertex set of adjacent vertices is the following:
0 {1, 2}The above must be a digraph, because 0 is adjacent to 1 but 1 is not adjacent to 0. The graph looks like the following (with '+' for arrowhead):
1 {2, 3}
2 {}
3 {0, 1, 2}
0----+1
|+ /+
| \ / |
| X |
| / \ |
++ \+
2+----3
One way to represent a graph is as an array of linked lists:
0 --> 1 --> 2In general, the vertices in each list are not necessarily sorted.
1 --> 2 --> 3
2
3 --> 0 --> 1 --> 2
Another way to represent a graph is to use an adjacency matrix of boolean values to represent a graph.
If the graph contains an edge from 0 to 1, then row 0, column 1 should
be True. For instance, the above graph can be represented in the following
matrix:
| \ | 0 | 1 | 2 | 3 |
| 0 | F | T | T | F |
| 1 | F | F | T | T |
| 2 | F | F | F | F |
| 3 | T | T | T | F |
In both implementations, if the vertices are not sequentially numbered, but labeled in another way, some kind of mapping between the two will be needed.
Complexity in terms of |V| and |E|: