Diagram storage structure
1. The adjacency matrix
The adjacency matrix is very simple, suppose we have n variables, then we create an n*n matrix G. Assuming that the arc is <i,j>, then we can judge whether this arc exists by the value of the matrix G[i][j]. For example, for arcs that do not exist, we set the value as 0, and for existing arcs as 1, and if there is a right, it is its right.
For example, the graph shown in the figure below, expressed as an adjacency matrix, is:
∣ 0 1 0 0 1 0 1 1 0 0 0 0 0 0 0 0 ∣ \begin{vmatrix} 0 & 1 &0 &0 \\ 1&0 &1 &1 \\ 0&0 &0 &0 \\ 0&0 &0 &0 \end{vmatrix} ∣∣∣∣∣∣∣∣0100100001000100∣∣∣∣∣∣∣∣
We can think of this picture as:
This is easy to understand.
If it is an undirected graph, we only use a diagonal matrix.
2. Adjacency list
1. Adjacency list
Suppose we create a data type for the node, and then the arc pointed to by the node is also a data type, called 表结点
sum respectively 头结点
, then we can express it like this: the info is optional and used to store other information, such as the weight of the arc.
Suppose that in order to realize this graph:
we first create vertex nodes in order, and the value in parentheses is the index stored in the order of our nodes.
Add all arcs of A:
add all arcs of B: the
same, and the final completion is: the
adjacency list is very easy to find the first adjacent point and the next leading point of any vertex. But if you want to determine whether there are edges or arcs connected, especially edges, it is very troublesome.
2. Inverse adjacency list
Before learning the storage method of cross-linked list, it is helpful to understand the concept of cross-linked list.
It's still this graph, or this storage method, but the arc is changed in another direction. For example, the inverse adjacency table in the above figure is:
Three. Cross Linked List
Simply put, the cross-linked list combines the adjacency list and the inverse adjacency list into one. Generally used for directed graphs.
Its storage structure is:
tailvex
: Arc end
headvex
: Arc head
hlink
: The next arc with the same arc head : The next arc with the same
tlink
arc end
info
: Still the information of the arc
We still create the vertices in order first:
and then create an arc for each vertex according to the arc tail:
then we tlink
point 0, 1, 2, 3 to the same value, tailvex
and hlink
point to the same value headvex
. For example:
This constructs a table. Maybe my picture is not very good-looking, look at other versions:
Four. Adjacent multiple tables
We use this method to store node edges and vertices. mark
When it is used to traverse, determine whether it has been traversed and mark the variable.
ivex
The sum jvex
is the vertex value of the current edge, ilink
pointing to the same ivex
edge, jlink
pointing to the same jvex
edge.
Let's take a look at this picture:
Still create the vertex nodes in order:
Then still ivex
create each edge according to :
ilink
point to the same ivex
edge, jlink
point to the same jvex
edge: