Introduction and creation of graphs

Source: Internet
Author: User

first, the basic terminologyFigure: Consists of a poor, non-empty point set and a set of edges, which is simply written in G (V,e); Vertex: The vertex in the graph: there is no direction for each edge in the graph: there is a direction in each edge of the graph; no edge: The Edge is no direction, and is written as (A, B) has a forward edge: The edge is a direction, is written as an edge is also an arc; the beginning vertex is called the arc tail; Simple diagram: There is no graph pointing to itself, no two duplicate edges, no direction complete graph: There is an no-direction graph between each vertex, and a directed full graph: There are two opposite sides of each vertex, and the sparse graph: a graph with few edges relative to the vertex; dense graph: a lot of graphs; Weight: The edges in the graph may have a weight, in order to distinguish the length of the edge; NET: the number of edges connected to a particular vertex; degrees: the degree to which a given graph is defined, the number of edges at which this vertex is the starting point, and the number of edges that the vertex is the end of. Ring: The same path as the first vertex and the last vertex; a simple ring: a ring with no repeating vertices after the first vertex and the last vertex are removed; connected graph: Any two vertices are connected to each other graph; maximal connected sub-graph: Contains possibly many vertices (must be connected), that is, cannot find another vertex, Enables this vertex to connect to any vertex of this maximal connectivity sub-graph; connected component: The number of maximal connected sub-graphs; strong connectivity graph: This is the concept of a forward graph, which represents any two vertices, a, b, so that a can be connected to the B,b can also be connected to a graph; Spanning tree: n vertices, n-1 edges, and ensure that n vertices are interconnected (there is no ring); minimum spanning tree: the sum of the weights of the edges of this tree is the smallest of all spanning trees; AOV Network: Nodes represent the network of activities; AOE Network: The network that represents the duration of the activity ;-------------------------------------------------------------------------------- second, create the storage of the diagram:1, adjacency Matrix Method://graph Edge number of a long, there is a map/no map/a forward/non-network can be used to store it. However, it is not suitable for this method when the number of edges is low, resulting in wasted space

The adjacency matrix of a graph is stored in two arrays to represent the graph. A one-dimensional array stores the vertex information in a graph, and a two-dimensional array (adjacency matrix) stores information about edges or arcs in the diagram.

Figure G has n vertices, then the adjacency matrix is a n*n square, defined as:

Looking at an instance, the left is a graph without a direction.

As can be seen from the above, the edge array of the non-graph is a symmetric matrix. The so-called symmetric matrix is the element of n-order matrix satisfies AIJ = Aji. That is, from the upper-left corner of the matrix to the lower-right corner of the main diagonal axis, the upper-right corner of the element and the lower-left corner of the corresponding elements are all equal.

From this matrix, it is easy to know the information in the graph.

(1) It is easy to judge whether any two vertices have a boundless edge;

(2) To know the degree of a vertex is actually the sum of the elements of this vertex VI in the first row or (column i) of the adjacency matrix;

(3) Finding all the adjacency points of Vertex VI is to scan the element I of the matrix once, Arc[i][j] 1 is the adjacency point;

and the direction of the map to pay attention to the degree and the degree of the Vertex VI in the degree of 1, just is the sum of the number of the first column I. The dimension of vertex VI is 2, which is the sum of the number of rows I.

If figure g is a network Diagram with n vertices, then the adjacency matrix is a n*n square, defined as:

The wij here represents the weight on the (VI,VJ). Infinity represents a value that is allowed by a computer to be greater than all the weights on the edge, which is an impossible limit value. The left image below is a forward graph, and the right image is its adjacency matrix.

Here is the code implementation:#include #include#include#define NUM; #define BIG 22365;   typedef ENUM{DG,UNG,DN,UDN} Graphtype;      The type of graph typedef int VRTYPE;    Vertex type typedef int *INFOTYPE; Related information types for edges //define vertex relationship typestypedef struct arccell{int arckink; The type of the edge, that is, the vertex relationship type, the graph is 1/0, and the table is adjacent.   No-Net-weighted//infotype info; Point to all relevant information on that side}arccell; //Definition of non-direction graph/Nettypedef struct{GRAPHTYPE Gkind;   Type of diagram Vrtype Vr[num];  Store all vertices arccell arc[num][num];  Store all sides int vrnum,arcnum; The number of vertices and edges}graph; --------------------------------- The position of a vertex in an arrayint locate (Graph G,vrtype v) {int i;    for (i=0;ivrnum;i++) if (g->vr[i]==v) break;    if (i>=g->vrnum) return-1; else return i;} -------------------------------- //Create a no-map/Netint  createudn (graph G) {   scanf ("%d%d", &vrnum,&arnum);  //Enter the number of vertices and edges and the number of edge related information    for (i=0;i      scanf ("%d", &vr[i]);   for (i=0;i      for (j=0;j        arc[i][j]={big,null};    for (i=0;i        scanf ("%d%d%d", &vr1,&vr2,&arckink);  //input vertex relationship type         j=locate (G,VR1);  //positioning two vertices         k=locate (G,VR2);  //input vertex relationship type         if (i!=-1&&j!=-1) { //Both vertices exist           & nbsp g->arc[j][k]->arckink;                     g->arc[j][i]- >artype=G->arc[i][j]->artype;  //copy information to its symmetric edge             g->arc[j][i]->info=g->arc[i][j]->info;        }   }    return 0;} ----------------------------  //Create a forward graph/net. Similar to creating a no-go graph/NET, but in the end it is not necessary to copy information to its symmetric arc. Do not repeat again create int createdn (graph g) {return 0;}-------------------------int creategraph (graph G) {//Select the type of diagram to store switch (G->gtype)      {Case Dg:createng (G);      Case Ung:createung (G);      Case Dn:createdn (G);      Case UDN:CREATEUDN (G);   Default:return ERROR; }} int main ()//main function.    {Graph G;    Creategraph (G); return 0;} -------------------------------------------------------------------------------------------------- 2. Adjacent table method:Neighbor Table method solves the disadvantage of adjacency matrix, but for each vertex, it is easy to find out, but it is necessary to traverse the whole graph to find it. Therefore, the adjacent table method is not suitable for the map/net storage. No Graph/NET can be stored, simple than the cross-linked list method

The adjacency table is handled in such a way that:

(1) The vertex is stored in a one-dimensional array, of course, vertices can also be stored in a single-linked list, but the array can easily read the vertex information, more convenient.

(2) All the adjacency points of each vertex vi in the figure constitute a linear table, because the number of adjacency points is variable, so, with single-linked list storage, the non-direction graph is called Vertex vi edge table, the graph is called Vertex VI as the edge of the arc tail table.

For example, it is the structure of an adjacency table of an unstructured graph.

As you can see, the nodes of the vertex table are represented by the data and Firstedge two fields, which is the information field, which stores the vertices, and Firstedge is the pointer field, which points to the first node of the edge table, that is, the first adjacency point of the vertex. Benzi nodes are composed of Adjvex and next two domains. Adjvex is the adjacency point field, which stores the index of the adjacency point of a vertex in the vertex table, and next stores a pointer to the next node in the edge table.

For the graph with weighted value, you can add a weight data field in the Edge table node definition and store the weight information. As shown in.

For the adjacency table structure, the code for building the diagram is as follows.

#define BIG 26655; #define NUM 20; typedef char Vrtype; A vertex is a character when it cannot be a newline character, because the output characters are wrapped in a typedef int *infotype; //define vertex relationship typestypedef struct arccell{int tail;      int weight; The non-direction net is the weighted value, and the non-direction graph does not need.   InfoType info; Point to the edge all relevant information struct Arccell *next;} Arccell; //define vertex typestypedef struct {Vrtype data; Arccell *firstarc;} Vrcell; //define the Graph/NET typetypedef struct{   vrcell Vr[num];  //store all vertices    int vrnum,arcnum;  //vertex and Edge number}graph;   void creategraph (Graph g) {    int I, J, k;    Edgenode *e;    Edgenode *f; //&N bsp;printf ("Input vertex count and number of sides: \ n");    scanf ("%d,%d", &g->numvertexes, &g->numedges);     for (i = 0; i < g->numvertexes; i++)    //input vertex information     {       //printf ( "Please enter vertex%d:\n", i);        g->adjlist[i].data = GetChar ();        g->adjlist[ I].firstedge = NULL;    //Set side table to empty table          while (g->adjlist[i].data = = ' \ n ')         {             G->adjlist[i].data = GetChar ();       }   }&N bsp;   //Establish side table     for (k = 0; k < g->numedges; k++)     {        PRI NTF ("Input Edge (VI,VJ) on theVertex number: \ n ");        Char P, q;        p = getchar ();        Whil E (p = = ' \ n ')         {            p = getchar ();      &NBS P }        q = GetChar ();        while (q = = ' \ n ')         {            q = GetChar ();       }        int m, n;        m = Locate (g, p);        n = Locate (g, Q);        if (m = =-1 || n = =-1)         {            return;       }       //memory request space, generating edge table nodes         E = (Edgenode *) malloc (sizeof (Edgenode));    &N Bsp   if (e = = NULL)         {            fprintf (stderr, "malloc () error . \ n ");            return;       }       //adjacency sequence number is j        E->adjvex = n;       //The E pointer points to the structure of the current vertex         E->next = G-&gt ;adjlist[m].firstedge;       //pointing the current vertex pointer to e        G->adjlist[m].firstedge = e;          f = (Edgenode *) malloc (sizeof (Edgenode));  //Map/Net This step is not required         if (f = = NULL)         {        &N Bsp   fprintf (stderr, "malloc () error.\n");            return;       }         F->adjvex = m;        F->next = g->adjlist[n].firstedge;  &N Bsp     G->adjlist[n].firstedge = f;   }} ------------------------------------------------- ---------------------------------------  3, the cross-linked list method:The cross-linked list (orthogonal list) is a storage method of the graph, which is actually a combination of the adjacency table and the inverse adjacency table, that is, the edge nodes of each edge are organized into the linked list with the vertex of the arc tail as the head node and the linked list with the overhead point of the arc. In the cross-linked list representation, the node structure of the vertex table and the edge table is shown in 8.13 (a) and (b) respectively. There are five fields in the arc junction: where the Tail field (Tailvex) and the Head (Headvex) respectively indicate the position of the arc tail and the arc head in the diagram, the Chain field hlink points to the next arc of the same arc, the chain field tlink the next arc with the same arc, and the info field points to the relevant letter of the arc. Interest. Arcs with the same arc on the same linked list, arcs with the same arc on the same linked list. Their head node is the vertex node, which consists of three fields: the vertex field stores and vertex-related information, such as the name of the vertex, etc. firstin and Firstout are two chain fields, each pointing to the first arc node with that vertex as the arc head or the end of the arc. For example, Figure 8.14 (a) shows the cross-linked list shown in Figure 8.14 (b). If the adjacency matrix of a forward graph is considered a sparse matrix, then the cross-linked list can also be regarded as the adjacent matrix of the linked list storage structure, in the graph of the cross-linked list, the ARC node is located in the list of non-circular linked table, the relative position between nodes naturally formed, not necessarily by the vertex ordinal order, the table head node is the vertex node, they are stored sequentially. The form of the cross-linked list storage representation of a graph is described as follows: #define Max_vertex_numtypedef struct ARCBOX {int Tailvex,headvex;struct Arcbox * hlink, Tlink;/arc of the same arc head and the arc of the end of the chain domain * *InfoType info;}arcbox;typedef struct VEXNODE {vertextype Vertex:Arcbox Fisrin, firstout;}Vexnode;typedef struct {Vexnode Xlist[max_vertex_num];int vexnum,arcnum;}olgraph;  The following is an algorithm for creating a cross-linked list store with a graph. Through this algorithm, as long as the information of n Vertex and E arc are entered, the cross-linked list of the graph can be established, and the algorithm content is as follows. void Createdg (lograph **g){ scanf (& (*g->brcnum),& (*g->arcnum), &incinfo);For (i=0;i<*g->vexnum;++i){ scanf (& (G->xlist[i].vertex));*g->xlist[i].firstin=null;*g->xlist[i].firstout =null;           }For (k=0;k{scanf (&v1,&v2);I=locatevex (*G,V1); J=locatevex (*G,V2);p= (arcbox*) malloc (sizeof (Arcbox));*p={I,j,*g->xlist[j].fistin,*g->xlist[i].firstout,null}*g->xlist[j].fisrtin=*g->xlist[i].firstout=p;if (incinfo) Input (p->info);}} in the cross-linked list is easy to find in the tail arc, but also easy to find a VI head arc, it is easy to obtain the vertex of the degree and the degree of penetration (or need, can be found in the establishment of the cross-linked list). At the same time, it is known from algorithm 8.3 that the temporal complexity of establishing a cross-linked list is the same as that of establishing adjacency table. The cross-linked list is a useful tool in some of the graph-aware applications.

Introduction and creation of the diagram

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.