The storage structure of graphs
This article focuses on the depth-first search (DFS) and breadth-first search (BFS), so it is no longer to introduce the basic concepts of the graph too much, but to get a general idea of some of the common storage structures in the diagram below.
Adjacency Matrix
The adjacency matrix can be used both to store the graph without direction and to store the graph. In fact, the structure uses a two-dimensional array (adjacency matrix) to store the relationship between vertex information and vertices (edges of an arc with a direction graph or a direction-free graph). Its descriptive form is as follows:
The adjacency matrix storage of graphs represents
#define MAX_NUM 20//MAX vertex number
enum GRAPHKIND{GY,GN};//{forward graph, non-graph}
typedef struct
{
Vrtype adj; The vertex relation type. For unauthorized graphs, use 1 (yes) or 0 (no) to indicate whether they are adjacent, and for weighted graphs, the weights are
infotype *info;//pointers to the relevant information of the arc or edge (may not)
}arccell,adjmatrix[max_num][max_num]; Two-dimensional array
typedef struct
{
vertextype vexs[max_num];//vertex vector
adjmatrix arcs;//adjacency Matrix
int Vexnum, Arcnum; The current vertex number of the graph and the arc (edge) number
graphkind kind;//diagram of the kind of symbol
}graph;
We look at the following two graphs, the left is a direction graph, the right is a non-direction graph
The above two graphs are all unauthorized graphs, we assume that when storing, the V0 ordinal number is the 0,V1 ordinal number is the 1,v2 ordinal number is 2 ... , and adj 1 means that there is no connection between the two vertices, and 0 indicates a connection. Then the adjacency matrix of the direction graph is shown in the Matrix to the left of the graph, and the adjacency matrix of the graph is shown as the matrix to the right of the figure below.
According to the adjacency matrix, it is easy to determine the connectivity between any two vertices in the graph, and the degree of each vertex can be obtained.
1, for the direction-free graph, the right matrix is observed, and the degree of Vertex VI is found to be the sum of the elements of line I (or column i) in the adjacency matrix.
2, for the direction of the graph, due to the need to calculate the degree and into the reading, looking at the matrix on the left, we find that the Vertex VI is the sum of the rows of the adjacency matrix, and the entry is the sum of the elements of the adjacency matrix, so the degree of Vertex VI is the sum of the line I elements and the column I elements in the adjacency matrix.
Obviously, the storage space occupied by the adjacency matrix is independent of the number of edges or arcs, so it is suitable for dense graphs with many edges or arcs.