"C + + algorithm/data structure" adjacency matrix representation Graph, depth, breadth first traversal algorithm design + code + Picture __java

Source: Internet
Author: User

Http://wenku.baidu.com/link?url=fCPps803r8as33U38hMJ8ZtekPooj76vScbCtvS_PMO7FNdgmXhAeQlbeJT_ Jzqumgfk4awugruufsumjpjpuycu-oikupb4gacowlvcyno

* Problem Description:

Establish the storage structure of the diagram (the type of diagram can be a forward graph, non-direction graph, forward net, no network, students can choose two kinds of types, can input the vertex and edge of the graph information, and stored in the corresponding storage structure, and then output graph adjacency matrix.

 

1. Adjacency Matrix notation:

Set g= (v,e) is a diagram in which v={v1,v2,v3...,vn}. The adjacency matrix of G is a n-order square with which he has the following properties:

1, if (VI,VJ) ∈e or <Vi,Vj>∈E;

a[i,j]={

0, conversely

The adjacency matrices of the G1 and G2 graphs in Fig. 5-2 are M1 and M2 respectively:

M1=┌0 1 0 1┐

│1 0 1 0│

│1 0 0 1│

└0 0 0 0┘

M2=┌0 1 1 1┐

│1 0 1 0│

│1 1 0 1│

└1 0 1 0┘

Note that the adjacency of an M2 graph is a symmetric matrix, such as a.

When a graph with n vertices is represented by adjacency matrix notation, in addition to storing adjacent relations between vertices with n*n elements in the adjacency matrix, it is often necessary to set another vector to store n vertices. The type is therefore defined as follows:

Vertextype Vertex[max_vertex_num]; Vertex vectors

Adjmatrix arcs; Adjacency Matrix

int Vexnum, arcnum; Number of current vertices and arcs (edges) of graphs

Graphkind kind; Kind of symbol of the diagram

If each vertex in the graph contains only one number I (1≤i≤vnum), then only a two-dimensional array representing the adjacency matrix of the graph. The storage structure can be described briefly as follows:

Type adjmatrix=array[1..vnum,1..vnum]of adj;

It is easy to determine whether an edge (or arc) is connected between any two vertices by using the adjacency matrix, and the degree of each vertex is easily obtained.

For the direction-free graph, the degree of Vertex VI is the sum of the first line elements in the adjacency matrix, i.e.

n N

D (Vi) =∑a[i,j] (or ∑a[i,j])

J=1 I=1

For a direction graph, the Out OD (vi) of Vertex VI is the sum of the rows of the adjacency matrix, and the entry ID (vi) of Vertex VI is the sum of the column I elements. That

n N

OD (vi) =∑a[i,j], OD (vi) =∑a[j,i])

J=1 j=1

The adjacency matrix can also represent a weighted graph, as long as the

Wij, if <Vi,Vj> (VI,VJ)

a[i,j]={

∞, otherwise.

Where Wij is the weight value on <Vi,Vj> or (VI,VJ). Correspondingly, the definition of the type of the adjacency matrix of the net should be modified as follows: Adj:weightype; {Weightype is the right type}

Figure 5-6 lists a network and its adjacency matrix.

┌∞31∞∞┐

│∞∞51∞│

│∞∞∞∞∞│

│∞∞6∞∞│

└∞322∞┘

(a) network (b) adjacency matrix

Fig. 5-6 NET and its adjacency matrix

For the direction-free graph or the non-direction network, because its adjacency matrix is symmetrical, it can be stored in a compressed storage method, only the lower triangular or upper triangular elements (but not the elements on the diagonal) can be used. Obviously, the spatial complexity O () of the adjacency matrix notation.

The method of constructing the adjacency matrix of the non-network is to first initialize each element of matrix A to ∞. Then, read the edges and weights (i,j,wij) and place the corresponding elements of a into wij.

2, the graph traversal:

* Depth First Search

The depth-first search traversal is similar to the first root traversal of a tree, which is the generalization of the tree's first root traversal. Assuming that the initial state is that all vertices in the graph have not been accessed, the depth-first traversal can proceed from a vertex v of the graph, access this vertex and then proceed from the unreachable adjacency Point of V to the depth first to traverse the graph until all the vertices in the diagram and V have paths are accessed; The above procedure is repeated until all vertices in the diagram are accessed, as an inaccessible vertex in the other diagram.

The process of depth-first traversal of graphs is shown in Fig. 7.13 (b), as an example of G4 graph 7.13 (a). Based on the vertex V1, after accessing the vertex V1, the adjacency point V2 is chosen. Because the V2 has not been accessed, the search starts from V2. And so on, then search from V4,V8,V5. After accessing the V5, the search returned to V8 because the neighboring points of the V5 had been accessed. For the same reason, the search continues back to V4,v2 until V1, at which point the search went from V1 to V3, as another contiguous point of V1 was accessed. The access sequence from which the vertex is obtained is:

V1v2 v4v8v5v3v6v7

Obviously, this is a recursive process. In order to make it easy to distinguish whether the vertex has been accessed in the traversal process, an array of access flags must be attached to the visted[0...n-1], whose initial value is 0, and when a vertex is accessed, the corresponding component is set to 1.

* Breadth First Search

Assuming that from a vertex v in the diagram, each of the inaccessible extended adjacency points of a visit v after a visit to V are then accessed from these adjacent points sequentially to their adjacent points, and the "adjacency Point first accessed" is accessed after the "adjacency point" visited, The adjacent points of all the vertices that have been accessed in the diagram are accessed. If a vertex is not yet accessed in the diagram, a vertex that has not been accessed in the other diagram is used as the starting point, repeating the process until the vertices in the diagram are accessed. In other words, the process of the breadth-first traversal graph is to take V as the starting point, to be as far as near, to sequentially access and V to have the path to communicate and the path length is 1, 2 ... The vertices. For example, the breadth-first search traversal of the graph G4, as shown in Figure 7.13 (3), first accesses the adjacent Points V2 and V3 of the V1 and V1, and then accesses the V2 and V4 adjacent points v5 the adjacent points V3 and V6, and finally the V7 adjacent points v4. Because the adjacency points of these vertices have been accessed, and all vertices in the graph are accessed, this completes the traversal of the graph. The resulting vertex access order is listed as

V1v2 V3 V4 v5v6 V7 V8

Similar to depth-first search, an array of access flags is also required during traversal. Also, for sequential access path lengths of 2, 3 、... Vertex, you need to have the queue attached to store the path length 1, 2 that has been accessed ... The vertices.

2, the output of the diagram

The adjacency matrix of the graph is a two-dimensional array, which uses the nesting of the for statement to output sequentially.

 

 

 

 

 

 

 

Begin

Begin

Input Vexnum,arcnum

Incinfo

I=i+1

Select the type of diagram

Construction diagram


Input vertex

I<vexnum

Y

Depth traversal


Breadth traversal

J=j+1

N

I<vexnum

Initialize the neighbor

Connection matrix


End

Y

J<vexnum

N Y

I=i+1

N Main program Flowchart

K<arcnum

K=k+1


Enter information for arcs

Set adjacency matrix

Y

N

End


Structure Flowchart of graphs

1. The algorithm of constructing the adjacency matrix of the non-direction graph is as follows:

Procedure Build-graph; {Establish adjacency matrix for non-direction graphs}

Begin

For I:=1 to n do read (g.vertex[i); {Read the information for n vertices}

For I:=1 to N do

For J:=1 to E do

g.arcs[i][j]=0;

{Initializes each element of the adjacency matrix to 0}

The number of k:=1 to E do {e as edges}

[Read (i,j,w) {reading Edge <i,j> and right}g.arcs[i][j]:=w]

g.arcs[i][j]=g.arcs[i][i]{Symmetrical Arc}

End

The execution time of the algorithm is O (n+n2+e), in which the time spent on the initialization operation of the adjacency matrix is O (N2) and e<n2, so the time complexity of the algorithm is O (N2).

2. The algorithm for constructing the adjacency matrix of the non-network is as follows:

Procedure Build-graph; {Establish adjacency matrix for non-network}

Begin

For I:=1 to n do read (g.vertex[i); {Read the information for n vertices}

For I:=1 to N do

For J:=1 to E do

G.arcs[i][j]=maxint;

{Initializes each element of the adjacency matrix to Maxint, and the computer ∞ uses the most important number maxint to represent}

The number of k:=1 to E do {e as edges}

[Read (I,J,W) {reads the Edge <i,j> and right}g.arcs[i][j]:=w; G.arcs[i][j]:=w]end;

The execution time of the algorithm is O (n+n2+e), in which the time spent on the initialization operation of the adjacency matrix is O (N2) and e<n2, so the time complexity of the algorithm is O (N2).

3, the graph depth first traversal algorithm analysis

Begin

For I:=1 to N Do (Visited[i]) {Initialize flags array}

while (I<n)

{For:i=1 to n do{access adjacent points as required}}

End

When a two-dimensional array is used to represent the storage structure of the adjacency matrix, the time required to find the adjacency point of each vertex is O (n2), where n is the number of vertices in the graph.

4, the graph breadth First traversal algorithm analysis

Begin

For I:=1 to N Do (Visited[i]) {Initialize flags array}

while (I<n)

{For:i=1 to n do{if.....if ...}}

End

The two-dimensional array represents the storage structure of the adjacency matrix mapping, where n is the number of vertices in the graph, and the time required to find the adjacency point of each vertex is O (n2).

* GRAPH.H * *

#include <stdio.h>

#include <malloc.h>

#include <conio.h>

#include <stdlib.h>

#include <string.h>

#define ERROR 0

#define OK 1

#define MAX_VERTEX_NUM 20//MAX value defined

#define INFINITY 32768//MAX value defined

#define MAX_INFO 20

Typedefint Vrtype; Defining a new Type

Typedefint InfoType;

Typedefchar Vertextype;

Typedefenum

{DG,DN,UDG,UDN} graphkind;//graph, Direction net, non-direction graph, no-direction net

Typedefstruct Arccell

Each data structure of the {//adjacency matrix notation

Vrtype adj; The vertex relation type. For unauthorized graphs, use or indicate adjacent no, or weighted graph, the weight value type.

InfoType *info; A pointer to the ARC-related information

} Arccell, Adjmatrix[max_vertex_num][max_vertex_num];

Typedefstruct

{

Vertextype Vertex[max_vertex_num]; Vertex vectors

Adjmatrix arcs; Adjacency Matrix

int Vexnum, arcnum; Number of current vertices and arcs (edges) of graphs

Graphkind kind; Kind of symbol of the diagram

} mgraph;

Typedefstruct

{//Set stack

int Elem1[max_vertex_num];

int top;

}seqstack;

int Locatevertex (mgraph g,vertextype v);

void Createudg (Mgraph &g);

void Createudn (Mgraph &g);

void DepthFirstSearch1 (Mgraph G);

void BreadthFirstSearch1 (Mgraph G);

int creategraph (mgraph &g);

void Display (Mgraph G);

* Graph.cpp * *

#include "Graph.h"

int Locatevertex (mgraph g,vertextype v)

{//used to return the value represented by the ARC endpoint

int j=0,k;

for (K=0;K<G.VEXNUM;++K)

if (G.VERTEX[K]==V)

{j=k;break;}

return (j);

}

void Createudg (Mgraph &g)

{///using Array (adjacency matrix) notation to construct a non-direction graph

int i,j,k,incinfo;

I,j,k is a counter, incinfo is a marker

Char ch; Used to eat extra characters.

Vertextype V1,v2; Two vertices of the arc used to place the input

printf ("Please enter the number of vertices, number of edges, arcs containing relevant information (yes:, no:): \ n");

scanf ("%d,%d,%d", &g.vexnum,&g.arcnum,&incinfo);

Ch=getchar (); Used to eat a carriage return

printf ("Please enter a value of%d vertices (1 characters, space separated): \ n", g.vexnum);

for (i=0;i<g.vexnum;++i)//constructing vertex vectors

{

scanf ("%c", &g.vertex[i]); Ch=getchar ();

}

printf ("Enter the vertex vertices of the%d edges (in spaces): \ n", g.arcnum);

for (i=0;i<g.vexnum;++i)//initialization of adjacency matrices

for (J=0;J<G.VEXNUM;++J)

{

g.arcs[i][j].adj=0;

G.arcs[i][j].info=null; {Adj,info}

}

for (K=0;K<G.ARCNUM;++K)

{

scanf ("%c%c", &v1,&v2);

Ch=getchar ()//ch eats the return character

I=locatevertex (G,V1); J=locatevertex (G,V2);

if (incinfo) scanf ("%d", &g.arcs[i][j].info);

G.arcs[i][j].adj=g.arcs[j][i].adj=1; Symmetrical arc <v2,v1> of placing <v1,v2>

}

}//createudg

void Createudn (Mgraph &g)

{///using Array (adjacency matrix) notation, constructing the non-network

int i,j,k,w,incinfo;

I,j,k for counters, w for drop weights, incinfo for markers

Char ch; Used to eat extra characters.

Vertextype V1,v2;

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.