Graph data structure (adjacency list, adjacency matrix)

The basic concept of a
graph : A graph is a set composed of edge set E and point set V: G (V, E) G(V,E)G ( V ,E ) Undirected
edge:(vi, vj) (v_i,v_j)( vi,vj) ,有向边: < v i , v j > <v_i,v_j> <vi,vj>
Logical relationship: Thelogical relationship betweenpoints is adjacency, and adjacent points are called neighbors for short.
Simple graphs: Generally speaking, only simple graphs are discussed. The so-called simple graphs have no self-edges (self-pointing to themselves) and no repetitive edges. Self-edges and repetitive edges are mostly meaningless in computers and reality.
Graph classification: For graphs, there are three common classification methods:
whether the edges are weighted: weighted: net graph/net, unweighted: graph
whether the edges are directed:
whether any two points ofa directed graph or an undirected graphare reachable : Connected graph, unconnected graph
For unconnected graphs, unconnected subgraphs are called connected components. For each connected component, it must be a connected graph. As shown in the figure below: There are three connected components in a figure, and each connected component is a connected graph, as shown in figure b.
Insert picture description here

Graph data structure:
There are generally two data structures: adjacency matrix and adjacency table.
Adjacency matrix : generally a two-dimensional array vector<vector<type>> V, type is the data type of the node.
The adjacency matrix of the undirected graph : must be a symmetric matrix, in the non-net graph, V [i] [j] = 0, 1 V[i][j]=0,1V[i][j]=0,1 means edgeeij e_{ij}eijWhether it exists, in the network diagram, V [i] [j] V[i][j]V [ i ] [ j ] represents the edgeeij e_{ij}eijThe weight of, use 0 or ∞ ∞ for boundless means, as shown in the figure below:
Figure
Insert picture description here
adjacency matrix of a directed graph: generally asymmetric
Insert picture description here
Insert picture description here

Adjacency list : Each point has an adjacent point vector/linked list. I.e.
< vi v_{i}vi,vector<type>>, type is the data type of the point. If it is a net map, change the type to a binary dictionary map<type,int>, which is < vi v_{i}vi,vector<map<type,int>>>
generally uses a vector to save the neighbors of each point, and the linked list is not easy to access randomly.
For example, the adjacency lists of the above two directed graphs are:
Insert picture description here
I prefer to use the adjacency list to store the information of the graph. One is not easy to make mistakes (one-to-one correspondence between points and neighbors), and the other is for sparse graphs, The adjacency list saves more space and time when traversing!

Guess you like

Origin blog.csdn.net/weixin_42419611/article/details/106630291