Storage and traversal of graph of data structure algorithm (Java)

Source: Internet
Author: User

One: Figure of the Classification 1: No direction diagram

That is, there is no explicit pointing relationship between the two vertices, only one edge is connected, for example, a vertex and B vertex can be represented as <a, b> can also be represented as <b, A>, as follows


2: The Map

The vertices are directional, such as between A and b vertices, a points to the b,b also points to a, the two are different, if the edge is given weight, then this difference is more significant

=================================================================================================

On the second basis, according to the graph of connectivity can be divided into

Non-direction full graph: On the basis of an N-1 graph, there is an edge between each of the two vertices, a non-complete graph with n vertices, with a total number of edges of n ()/2

Forward full graph: On the basis of a forward graph, there is an edge between each of the two vertices, a forward complete graph with n vertices, with a total number of edges N (N-1)

Connected graphs: For undirected graphs, if any of the two vertices are connected, the undirected graph is called the connected graph

Non-connected graph: In undirected graphs, where there are two vertices that are not connected, the undirected graph is called a non-connected graph

Strongly connected graphs: for directed graphs, if there are any two vertices in the directed graph are connected (note direction problem, a->b, set up, but b->a not necessarily set), then the directed graph is called strong connected graph

Non-strongly connected graphs: if there are two vertices in the direction graph that are not connected, then the undirected graph is called a non-strong connected graph


Two: storage structure of graph 1: adjacency matrix

Use a two-dimensional array to store information and weights for the edges of the graph, such as the 4-vertex-free graph shown

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

If you change to a forward graph, the adjacency matrix of the five vertices of the forward graph is represented as follows

2: adjacency table

Adjacency matrix is a good graph storage structure, but for graphs with relatively few sides, this kind of structure has a great waste of space, so it is called adjacency table to find a storage method combining array with linked list.

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 the Vertex vi edge table, the forward graph is called Vertex VI as the edge of the arc tail table

The adjacency table for the graph is represented as follows:

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.


The adjacency table for the graph is represented by:


3: Cross-linked list

For adjacency tables, it is inconvenient to calculate the degree of vertex entry, so is there a way to easily calculate the degree of vertex penetration and the degree of exit, the answer is yes

The structure of the node is redefined in the cross-linked list:

Firstin represents the in-Edge header pointer, which points to the first node in the edge table of the vertex, Firstout represents the edge header pointer, and points to the first node in the edge table of the vertex

The redefined edge table structure is:

Where Tailvex refers to the beginning of the arc in the table below the vertex table, Headvex refers to the end of the arc in the vertex table subscript, headlink refers to the edge table pointer field, pointing to the same end point the next edge, Taillink refers to the edge table pointer field, pointing to the same starting point of the next edge. If it is a net, you can also add a weight domain to store the weights.

For example, the vertex is still stored in a one-dimensional array, and the solid arrow pointer is exactly the same as the adjacency table. With the vertex v0, Firstout points to the first node in the Out side table V3. So,v 0 side table Node Hearvex = 3, while Tailvex is actually the subscript 0 of the current vertex v0 , because v 0 there is only one out-of-edge vertex, and all headlink and Taillink are empty.

The emphasis needs to explain the meaning of the dashed arrows. It is actually the representation of the inverse adjacency table of this graph. Forv0, it has two verticesv1and thev2into the edge. So the firstin points to the vertexv1 2 1 2 , so its firstin points to the vertex v 2

The advantage of the cross-linked list is that the adjacency table and the inverse adjacency table are integrated together, so that it is easy to find a V-tail arc, but also easy to find a V-headed arc, so it is easier to calculate the vertex and the degree of penetration.

In addition to the complexity of the structure, in fact, the time complexity of creating the graph algorithm is the same as the adjacency table, therefore, in the application of the graph, the cross-linked list is a very good data structure model.

The above three kinds of storage structure, in addition to the third storage structure, the other two kinds of storage structure is relatively simple


Three: The traversal of graphs1: Depth-first traversal (DFS)

It starts at a node V, accesses the vertex, and then takes a depth-first traversal of the map from the inaccessible adjacency point of V until all the vertices in the diagram that are connected to the V are accessed. If there are still vertices in the graph that are not accessed, a vertex that has not been accessed in the diagram is used as a starting point, repeating the process until all the vertices in the diagram are accessed.

Basic Realization Idea:

(1) Access vertex v;

(2) A vertex w is selected from the inaccessible adjacency point of V, and the depth-first traversal is carried out from W;

(3) Repeat the above two steps until all the vertices in the diagram that are connected to the V are accessed.


Recursive implementation

(1) Access vertex v;visited[v]=1;//algorithm before execution visited[n]=0

(2) The first adjacency point of a w= vertex v;

(3) while (W exists)

if (w not accessed)

The algorithm is executed recursively from vertex W.
W= the next adjacency point of Vertex v;

Non-recursive implementation

(1) stack s initialization; visited[n]=0;

(2) Access vertex v;visited[v]=1; vertex v into the stack s

(3) while (stack s not empty)

x= stack s top element (not out of stack);

If (exists and finds the adjacency point of an inaccessible x W)

Access to W;visited[w]=1;

W into the stack;

Else

x out stack;



2: Breadth-first traversal (BFS)

It is a hierarchical search process and the hierarchical traversal of a two-fork tree is very similar, it also requires a queue to maintain the traversed vertex order, in order to access the vertices of the adjacent vertices in the sequence of the team.

Basic Realization Idea:

(1) Vertex v into the queue.

(2) Execution continues when the queue is non-empty, otherwise the algorithm ends.

(3) Out of the queue to get the team overhead point v; Access Vertex v and Mark Vertex v has been accessed.

(4) Find the first adjacency vertex of Vertex v Col.

(5) If the adjacent vertex of V Col is not visited, Col is queued.

(6) Continue to find another new adjacency vertex of Vertex v Col, go to step (5).

Until all the unreachable adjacency points of Vertex v have been processed. Go to step (2).

The breadth-first traversal graph is based on the Vertex v as the starting point, from near to far, in order to access and V has a path and the path length of 1, 2, ... The vertex. In order for the adjacency point of the first access vertex to be accessed before the adjacency point of the accessed vertex, set the vertex that the queue stores access to.


Pseudo code

(1) Initialize queue q;visited[n]=0;

(2) Access vertex v;visited[v]=1; vertex v into queue q;

(3) while (queue Q is not empty)

v= Queue Q of the enemy elements out of the team;

w= the first adjacency point of Vertex v;

while (W exists)

If W is not accessible, the vertex w is accessed;

Visited[w]=1;

Vertex w into the queue q;

W= the next adjacency point of Vertex v.


IV: Illustrative examples

Using adjacency matrix to store the edge information of graphs

/* Define the structure of the graph */class graph {static final int maxnum=20;        Maximum number of nodes static final int maxvalue=65535;char[] Vertex = new Char[maxnum];         Defines an array, saving the vertex information int GType;   Fig. 0: No direction figure  1: the graph int vertxnum;              The number of vertices int edgenum;         Number of edges int[][] Edgeweight = new Int[maxnum][maxnum];     Define matrix save vertex information int[] Istrav = new Int[maxnum];            Traversal flag}

Create adjacency matrix static void Creategraph (graph g) {int I,  j  ,  k;int weight;     Right char Estartv,  endv;      The starting vertex of the Edge System.out.println ("information for each vertex in the way"), for (i=0; i < g.vertxnum; i + +) {System.out.println ("+" + (i+1) + "vertex"), G. Vertex[i] = (Scan.next (). ToCharArray ()) [0];} System.out.println ("Enter vertices and weights that make up the passes"); for (k=0;k<g.edgenum;k++) {System.out.println ("+" + (k+1) + "sidebar:"); ESTARTV = Scan.next (). charAt (0); ENDV = Scan.next (). charAt (0); weight = Scan.nextint (); for (i=0; Estartv!=g.vertex[i]; i++);           Finds the start node in an existing vertex for (j=0; Endv! = G.vertex[j]; j + +);             Find the endpoint g on an existing node. EDGEWEIGHT[I][J] = weight;       The corresponding position holds the weight, indicating that there is an edge if (G.gtype = = 0)               //If it is a non-direction graph, the weight g is saved at the diagonal position. Edgeweight[j][i] = weight;}}

Empty diagram static void Cleargraph (graph g) {int i,j;for (i=0; i< g.vertxnum; i++) for (J =0; j<g.vertxnum; J + +) g.edgeweight[ I][J] = Graph.maxvalue;           Set the value of the MaxValue} in the Matrix

Output adjacency matrix static void Outgraph (Graph g) {int i,j;for (j = 0; J < G.vertxnum;j + +) System.out.print ("\ T" + g.vertex[j]);      In the first line, enter the vertex information System.out.println (); for (i =0; I <g.VertxNum; i + +) {System.out.print (g.vertex[i]); for (j = 0;j < G. Vertxnum; J + +) {if (g.edgeweight[i][j] = = Graph.maxvalue)    //If the weight is the maximum value System.out.print ("\tz");    Z denotes infinity elseSystem.out.print ("\ T" + g.edgeweight[i][j]);  The weight of the output edge}system.out.println ();}}

Traverse diagram static void Deeptraone (graph g,int N) {//From nth node to start traversing int i;g.istrav[n] = 1;              A mark of 1 indicates that the vertex has been processed System.out.println ("--" + g.vertex[n]); Output node data//Add processing node operation for (i = 0; i< g.vertxnum; i++) {if (G.edgeweight[n][i]! = G.maxvalue && G.istrav[n] = = 0) {Dee Ptraone (g, i);     Recursive Traversal}}}

Depth-first traversal of the static void  deeptragraph (Graph g) {int i;for (i = 0; i< g.vertxnum; i++) {g.istrav[i]= 0;} System.out.println ("depth-first traversal:"); for (i = 0; i< g.vertxnum; i++) {if (g.istrav[i] = = 0) deeptraone (g,i);} System.out.println ();}

Main function:

public static void Main (string[] args) {//TODO auto-generated method Stubgraph g = new Graph (); System.out.println ("Type of output generated diagram:"); g.gtype = Scan.nextint ();  The type of graph System.out.println ("number of vertices of the input graph:"); g.vertxnum = Scan.nextint (); System.out.println ("Number of sides of the input graph:"); g.edgenum = Scan.nextint (); Cleargraph (g)          ; Clear Figure creategraph (g);      Figure System.out.println ("adjacency matrix data for the graph") that generates the Adjacency table structure is as follows: "Outgraph (g);        Output Figure deeptragraph (g);    Depth-first traversal diagram}

To run the test results:

A forward graph test result (no graph similar, just enter 0 when entering the generated diagram type)


Full code: Click to view Download

Storage and traversal of graph of data structure algorithm (Java)

Related Article

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.