Depth-first traversal and breadth-first traversal of graphs based on adjacency matrix storage

Source: Internet
Author: User

The storage structure of the graph is much more complex than the linear table and the tree, and for the linear table, it is a one-on relationship, so it can be stored simply with arrays or linked lists. The tree structure is a one-to-many relationship, so we want to combine the attributes of the array and the list to better store it.

So our graph is a many-to-many case, and any vertex on the graph can be considered as the first vertex, and there is no order relationship between the adjacency points of any vertex.

Take a closer look at the following pictures, and then take a deep look:

Because there can be connections between any two vertices, it is not possible to represent the relationship between elements in the physical location of the data element in memory (the physical location of the memory is linear and the element relationship of the diagram is planar).

It can be done with a multi-linked list, but in the tree chapters before a few lessons we have already discussed that the sheer waste caused by a multi-linked list is unthinkable (if the degrees of each vertex vary too much, it can be a huge waste).

Adjacency Matrix (No map)

Considering that the graph is composed of vertices and edges or arcs, it is difficult to fit together, it is natural to consider the two structures to be stored separately.

Vertices because they do not distinguish between size, primary and secondary, so a one-dimensional array to store is a good choice.

A one-dimensional array must be out of order if the edge or arc is a relationship between vertices and vertices, so we might consider using a two-dimensional array to store it.

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

We can set two arrays, the vertex array is vertex[4]={v0,v1,v2,v3}, the Edge array arc[4][4] is a symmetric matrix (0 means there are no edges between vertices, and 1 means there are edges between vertices).

symmetric matrix: The so-called symmetric matrix is the element of n-order matrix satisfies a[i][j]=a[j][i] (0<=i,j<=n). 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.

With this two-dimensional array of symmetric matrices, we can easily know the information in the diagram:
    1. It is very easy to determine 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 row I (or column i) of the adjacency matrix;
    3. To find all the adjacency points of Vertex VI is to scan the matrix I-line element once, Arc[i][j] 1 is the adjacency point.

Adjacency Matrix (forward graph)

The edges of the non-graph form a symmetric matrix, seemingly wasting half of the space, if there is a map to store, will the resources are used very well?

Visible vertex Array Vertex[4]={v0,v1,v2,v3}, arc array arc[4][4] is also a matrix, but because it is a graph, so this matrix is not symmetrical, for example, from V1 to V0 arc, get arc[1][0]=1, and V0 to V1 no arc, so arc[0 ][1]=0.

In addition to the map is fastidious, to take into account the degree and the degree, the V1 of the vertex is 1, just the sum of the number of the V1 column, the vertex V1 the degree of 2, is exactly the sum of the number of the first V1 row.

Adjacency Matrix (NET)

In the terms of the graph, we refer to the concept of the net, in fact, each side of the graph with a right is called the net.

The following is an example of this no-map, using adjacency matrix storage and implementing depth-first traversal and breadth-first traversal:

The code is as follows:

#include <stdio.h>#defineMaxvex 100//maximum number of vertices#defineINFINITY 65535//represents ∞#defineTRUE 1#defineFALSE 0typedefCharVertextype;//Vertex typetypedefintEdgetype;//Weight value typetypedefintBool; Bool Visited[maxvex];typedefstruct{vertextype Vexs[maxvex]; //Vertex ArrayEdgetype Arc[maxvex][maxvex];//adjacency Matrix    intNumvertexes, Numedges;//number of nodes and sides in the current graph}mgraph;//breadth-first traversal of required loop queuestypedefstruct {    intData[maxvex]; intfront, Rear;} Queue;/****************************************///operations related to queues//InitializevoidInitqueue (Queue *Q) {Q->front = Q->rear =0;}//QueuevoidEnQueue (Queue *q,inte) {    if((q->rear+1)%maxvex = = Q->front)return ; Q->data[q->rear] =e; Q->rear = (q->rear+1)%Maxvex;}//empty sentenceBool Queueempty (Queue *Q) {    if(Q->front = = q->rear)returnTRUE; Else        returnFALSE;}//out TeamvoidDeQueue (Queue *q,int*e) {    if(Q->front = = q->rear)return ; *e = q->data[q->Front]; Q->front = (q->front+1)%Maxvex;}/****************************************///establishing adjacency matrices of graphsvoidCreatemgraph (Mgraph *G) {    intI, J, K, W; printf ("Enter the number of vertices and the number of edges:"); scanf ("%d%d", &G->numVertexes,&G->numedges);    Fflush (stdin); printf ("==============================\n"); printf ("enter each vertex: \ n");  for(i=0; i<g->numvertexes; ++i) {printf ("Vertex%d:", i+1); scanf ("%c", &G->Vexs[i]);    Fflush (stdin); }     for(i=0; i<g->numvertexes; ++i) { for(j=0; j<g->numvertexes; ++j) G-&GT;ARC[I][J] =INFINITY; } printf ("==============================\n");  for(k=0; k<g->numedges; ++k) {printf ("Subscript I and J and W in the input edge (VI, VJ):"); scanf ("%d%d%d", &i,&j,&W); G-&GT;ARC[I][J] =W; G->arc[j][i] = g->Arc[i][j]; }}//OutputvoidDismgraph (Mgraph *f) {    intI, j, K; K= g->numvertexes;  for(i=0; i<k; ++i) { for(j=0; j<k; ++j) {printf ("%5d", g->Arc[i][j]); } Putchar ('\ n'); }}/****************************************///Depth-first traversal of graphsvoidDFS (Mgraph G,inti) {    intJ; Visited[i]=TRUE; printf ("%c", G.vexs[i]);  for(j=0; j<g.numvertexes; ++j) {if(G.arc[i][j]!=infinity &&!)Visited[j])    DFS (G, J); }}voidDfstraverse (mgraph G) {inti;  for(i=0; i<g.numvertexes; ++i) visited[i]=FALSE;  for(i=0; i<g.numvertexes; ++i) {if(!Visited[i])    DFS (G, i); }}//breadth-first traversal of graphsvoidBfstraverse (Mgraph *G) {    intI, J;    Queue Q;  for(i=0; i<g->numvertexes; ++i) visited[i]=FALSE; Initqueue (&p);  for(i=0; i<g->numvertexes; ++i) {if(!Visited[i]) {Visited[i]=TRUE; printf ("%c", g->Vexs[i]); EnQueue (&Q, i);  while(! Queueempty (&Q) {DeQueue (&q, &i);  for(j=0; j<g->numvertexes; ++j) {if(!visited[j] && g->arc[i][j]!=INFINITY) {Visited[j]=TRUE; printf ("%c", g->Vexs[j]); EnQueue (&Q, J); }                }            }        }    }}/****************************************///Program EntryintMain () {mgraph G; Createmgraph (&f); printf ("\ n The depth-first traversal of the graph is:");        Dfstraverse (G); printf ("\ n The breadth-first traversal of the graph is:"); Bfstraverse (&G); printf ("\ n"); return 0;}

Operation Result:

Depth-first traversal and breadth-first traversal of graphs based on adjacency matrix storage

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: 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.