Storage structure of [PHP data structure] diagram

Time:2021-10-11

The concept of figure is almost introduced. You can digest it and continue to learn the following content. If there is no problem, we will continue to learn the next content. Of course, this is not the most troublesome place, because today we just introduce the storage structure of graphs.

Sequential storage structure of graphs: adjacency matrix

What is adjacency matrix

First, let’s look at how to store graphs in a sequential structure. Whether stack, queue or tree, we can use a simple array to realize the sequential storage capacity of these data structures. But the graph is different. From the last article, we learned that the representation of a node isThis form. If we think of this node as a point on a coordinate axis, can we use a two-dimensional array to represent it? Yes, let the first dimension of the two-dimensional array be represented as the x-axis and the second dimension as the y-axis, so that we can build a graph. Yes, there is another alias for this form of two-dimensional array: matrix.

In the term of graph, the sequential storage structure of graph represented by two-dimensional array is called adjacency matrix. Just like the table below.

https://imgs.developpaper.com/imgs/1575433-20210729090306664-1536863248.jpg

In this table, we have two horizontal and vertical coordinates. X1-4 and y1-4 indicate that there are four nodes in the figure. Through their corresponding relationship, we can see whether there is an edge between one node and another. For example, the pair of coordinates X1 and Y2, their value is 1, which means that there is an edge between node 1 and node 2. Here, we use an unauthorized graph, that is, 0 represents no edge and 1 represents an edge between two nodes. At the same time, it is also an undirected graph, soThe value of is also 1. Its intention is that there is also an edge from node 2 to node 1. If it is a directed graph, it is necessary to determine whether the edge is set to 1 according to the direction of the directed arrow.

What is the graph corresponding to the adjacency matrix above? You can try hand animation by yourself. It doesn’t matter if we can’t draw it, because we’re just beginning to learn. In fact, it is the adjacency matrix of the graph we first showed.

https://imgs.developpaper.com/imgs/1575433-20210729090306829-1378071820.jpg

The figure on the left is the corresponding adjacency matrix in the table above. So what is the adjacency matrix of the digraph on the right? Let’s write it, too.

https://imgs.developpaper.com/imgs/1575433-20210729090306994-1656254825.jpg

Interesting? So what if it’s a power map? In fact, it is very simple that we can directly replace 1 in the graph with the weight of the corresponding edge, but it is possible that the weight of some edges is 0, so in the weighted graph, we can define a very large number or a very small negative number as an infinite number to indicate that the two nodes have no edges.

Construct adjacency matrix

Next, we construct such a storage structure of adjacency matrix through code. We still use the example of undirected graph. Because the undirected graph needs the reverse nodes to assign values, it has one more step than the directed graph, and the others are basically similar.

//Adjacency matrix
$graphArr = [];
function CreateGraph($Nv, &$graphArr)
{
    $graphArr = [];
    for ($i = 1; $i <= $Nv; $i++) {
        for ($j = 1; $j <= $Nv; $j++) {
            $graphArr[$i][$j] = 0;
        }
    }
}

//Adjacency matrix
function BuildGraph(&$graphArr)
{
    Echo 'please enter the number of nodes:';
    fscanf(STDIN, "%d", $Nv);
    CreateGraph($Nv, $graphArr);

    if ($graphArr) {
        Echo 'please enter the number of sides:';
        fscanf(STDIN, "%d", $Ne);
        if ($Ne > 0) {
            for ($i = 1; $i <= $Ne; $i++) {
                Echo 'please enter an edge in the format of access right:';
                fscanf(STDIN, "%d %d %d", $v1, $v2, $weight);
                $graphArr[$v1][$v2] = $weight;
                //If it is an undirected graph, you also need to insert the opposite edge
                $graphArr[$v2][$v1] = $weight;
            }
        }
    }
}

In this code, first we initialize a two-dimensional matrix through the creategraph () method. That is, according to the number of nodes we enter, we implement an X * y two-dimensional array structure, and define that all its values are 0, that is, the graph has no edges at present.

Then, after the buildgraph () method calls creategraph (), we continue to enter the information of the edge. First enter the number of edges. We have several edges. If the edge is less than or equal to 0, do not continue to create. In fact, we can be a little more rigorous. According to the definitions of undirected holograph and directed holograph, the edges can not exceed the maximum limit.

Next, we will continue to input edge information circularly. The input format I need here is the output node, input node and weight of the edge. Since our example is an undirected graph, in addition toIn addition to creating edges, you also createCreate an edge. The code has been described in the comments.

The interpretation code may still be abstract. Just run it and try it.

BuildGraph($graphArr);
//Please enter the number of nodes: 4
//Please enter the number of sides: 4
//Please enter an edge in the format of access right: 1 2 1
//Please enter an edge in the format of access right: 1 3 1
//Please enter an edge in the format of access right: 1 4 1
//Please enter an edge in the format of access right: 3 4 1

print_r($graphArr);
// Array
// (
//     [1] => Array
//         (
//             [1] => 0
//             [2] => 1
//             [3] => 1
//             [4] => 1
//         )

//     [2] => Array
//         (
//             [1] => 1
//             [2] => 0
//             [3] => 0
//             [4] => 0
//         )

//     [3] => Array
//         (
//             [1] => 1
//             [2] => 0
//             [3] => 0
//             [4] => 1
//         )

//     [4] => Array
//         (
//             [1] => 1
//             [2] => 0
//             [3] => 1
//             [4] => 0
//         )

// )
//  x
//y 0 1 1 1
//  1 0 0 0
//  1 0 0 1
//  1 0 1 0

Invoke our PHP file in the command line environment, and input the relevant information in turn according to the contents of the prompt. Finally, the printed as like as two peas are in the same form as the ones in the above table. With a simple piece of code, we realize the sequential storage of graphs.

Some students may be confused for a while. Because I was completely confused when I first saw it, but I can figure it out right away by carefully comparing the drawing with the table above. This time we really entered the two-dimensional world. Is it that the feeling map threw the tree thousands of miles away in an instant. In the case of complete binary tree, our thought is two-dimensional, but the structure is one-dimensional. In the case of adjacency matrix, both thought and code structure have evolved into two-dimensional space, which is really not blowing on the height.

Linked storage structure of graph: adjacency list

After finishing the sequential storage structure, naturally we can’t ignore another form of storage structure, that is, the chain storage structure of graph. In fact, for a graph, the chain structure is very simple and clear, because we only need to know that one node and those nodes have edges. Then let’s make this node form a single linked list and link all the way back, as shown in the figure below. (similarly, the undirected graph in the above figure is taken as an example)

https://imgs.developpaper.com/imgs/1575433-20210729090307295-794561444.jpg

Starting from node 1, it points to a subsequent node 2, and then continues to link node 3 and node 4 backward. In this way, the edges related to node 1 are described. Because we still show the adjacency list representation of undirected graph, the linked list node of node 2 points to node 1. It’s doneThe reverse direction of the.

For code implementation, we can save the header node, that is, the formal 1-4 nodes, in a sequence table. Then let the value of each array element be the content of the first node. In this way, we can let the linked list node only save the node name, weight and the pointing information of the next node object.

//Head node
class AdjList
{
    public $adjList = []; //  Vertex list
    public $Nv = 0; //  Node number
    public $Ne = 0; //  Number of sides
}
//Edge node
class ArcNode
{
    public $adjVex = 0; //  node
    public $nextArc = null; //  Link to
    public $weight = 0; //  weight
}

https://imgs.developpaper.com/imgs/1575433-20210729090307538-1534765091.jpg

Next, let’s look at how to use the adjacency table structure to build a graph.

function BuildLinkGraph()
{
    Fscanf (stdin, "please enter the number of nodes and edges:% d% d", $NV, $NE);
    if ($Nv > 1) {
        //Initialize header node
        $adj = new AdjList();
        $adj->Nv = $Nv; //  Save it for easy use
        $adj->Ne = $Ne; //  Save it for easy use
        //Head node list
        for ($i = 1; $i <= $Nv; $i++) {
            $adj->adjList[$i] = null; //  Set all to null, a boundless empty graph
        }
        
        if ($Ne > 0) {
//
            for ($i = 1; $i <= $Ne; $i++) {
                Echo 'please enter an edge in the format of access right:';
                fscanf(STDIN, "%d %d %d", $v1, $v2, $weight);
                //Create a node
                $p1 = new ArcNode;
                $p1->adjVex = $v2; //  The node name is the incoming node
                $p1->nextArc = $adj->adjList[$v1]; //  The next hop points to the head node of the outgoing node
                $p1->weight = $weight; //  Set weight
                $adj->adjList[$v1] = $p1; //  Make the value of the head node equal to the newly created node

                //Undirected graph requires the following operations, that is, the reverse linked list should also be established
                $p2 = new ArcNode;

                //Notice the difference between the following two lines and the above code
                $p2->adjVex = $v1; //  This is the entry point
                $p2->nextArc = $adj->adjList[$v2]; //  This is the outgoing node
                
                $p2->weight = $weight;
                $adj->adjList[$v2] = $p2;
            }

            return $adj;
        }

    }

    return null;
}

The comments in the code are clear. It can be seen that in the operation of adjacency table, undirected graph is the same. It operates one step more than directed graph. If only directed graph is established, P2 node operation is not required. It should be noted that in this code, we use the header insertion method in the linked list operation. That is, the last piece of data will be inserted into the head node, and the earliest one will be at the end of the linked list. Let’s take a look at the output of the finally established data structure.

print_r(BuildLinkGraph());
// AdjList Object
// (
//     [adjList] => Array
//         (
//             [1] => ArcNode Object
//                 (
//                     [adjVex] => 4
//                     [nextArc] => ArcNode Object
//                         (
//                             [adjVex] => 3
//                             [nextArc] => ArcNode Object
//                                 (
//                                     [adjVex] => 2
//                                     [nextArc] => 
//                                     [weight] => 1
//                                 )

//                             [weight] => 1
//                         )

//                     [weight] => 1
//                 )

//             [2] => ArcNode Object
//                 (
//                     [adjVex] => 1
//                     [nextArc] => 
//                     [weight] => 1
//                 )

//             [3] => ArcNode Object
//                 (
//                     [adjVex] => 4
//                     [nextArc] => ArcNode Object
//                         (
//                             [adjVex] => 1
//                             [nextArc] => 
//                             [weight] => 1
//                         )

//                     [weight] => 1
//                 )

//             [4] => ArcNode Object
//                 (
//                     [adjVex] => 3
//                     [nextArc] => ArcNode Object
//                         (
//                             [adjVex] => 1
//                             [nextArc] => 
//                             [weight] => 1
//                         )

//                     [weight] => 1
//                 )

//         )

//     [Nv] => 4
//     [Ne] => 4
// )

Is the chain storage structure of the graph established by using the adjacency table clearer than the adjacency matrix. Just like the chain and sequential structures of trees, their advantages and disadvantages are similar in graphs. The adjacency matrix takes up more physical space because it requires two layers of arrays with as many elements. Like the table above, it needs to occupy a 4 * 4 physical lattice. In the adjacency table, we can directly count its node points, which only needs 12 grids. Moreover, more importantly, the linked adjacency table can expand the edge nodes and the number of edges at any time without re initialization. We only need to modify the above test code. If the number of nodes of the adjacency matrix needs to be modified, we have to re initialize the whole two-dimensional array.

summary

For graphs, in addition to adjacency matrix and adjacency table, there are other storage forms, but they are just some optimization and deformation of chain adjacency table. If you are interested, you can learn about the two storage structures of cross linked list and adjacent multiple list.

Well, the basic storage structure has been paved, and we are familiar with the concept of graph. Next, we are ready to do the most important operation, that is, how to traverse the graph.

Test code:

https://github.com/zhangyue0503/Data-structure-and-algorithm/blob/master/5. Figure / source / 5.2 storage structure of figure.php

reference material:

Data structure, Second Edition, Yan Weimin

Data structure, Second Edition, Chen Yue

High score notes on data structure, 2020 edition, tianqin postgraduate entrance examination

Official account: hard core project manager

Add wechat / QQ friends: [xiaoyuezigonggong / 149844827] get free PHP and project management learning materials

Tiktok, official account, voice, headline search, hard core project manager.

Station B ID: 482780532