Topology sequencing of data structures and algorithm 17

Source: Internet
Author: User

This article for Bo Master original article, reprint please indicate source:http://blog.csdn.net/eson_15/article/details/51194219


In this section we learn a new sorting algorithm, which, to be exact, should be called "topological ordering of the graph". The so-called graph is a->b, but B cannot reach a. The difference from the graph is that its edges have only one item in the adjacency matrix ( friendly tip : If you don't understand the data structure of the graph, you can first look at this blog post: data structure and algorithm of the non-direction diagram. Because topological ordering is based on diagrams of this data structure.

The adjacency matrix of a forward graph is shown in the following table:

A

B

C

A

0

1

1

B

0

0

1

C

0

0

0

So for the non-directed graphs discussed earlier, the upper and lower triangles of the adjacency matrix are symmetric, and half the information is redundant. And all the rows and columns in the adjacency matrix of the graphs contain the necessary information, and the upper and lower triangles are not symmetrical. So for a forward graph, the method of adding edges requires only one statement:

In the Addedge graph, there is only one public void in the adjacency matrix (int start, int end) {Adjmat[start][end] = 1;}
If the adjacency table is used, then a->b indicates that A has B in its list, but the list of B does not contain a, and there is not much to say, this article is mainly implemented by adjacency matrix.

Because the graph is forward, assuming a->b->c->d this, then this hides a sequence, that is, to think of D, must first cross C, must first cross B, must first over a. They virtually form a sequence, which in practice is quite extensive, for example, to do web development, you must first learn the basics of Java, and so on, which follow a sequence, so the idea of topological sorting is the same, using a map-specific order. But the result of topological sequencing is not unique, such as A->b, C->b, that is, a and C can go to B, so using the algorithm to generate a topological ordering, the use of the method and the details of the code determines the kind of topological ordering will be generated.

The idea of topological sequencing, though unusual, is simple, with two necessary steps:

1. Find a vertex that has no successor;

2. Delete this vertex, insert the vertex's marker in the list

Then repeat 1 and 2 until all vertices are deleted, and the order of the vertices displayed in the list is the result of topological ordering.

But we need to consider a special kind of graph: loop. That is a->b->c->d->a. This inevitably leads to the absence of a successor node, which prevents the use of topological ordering.

Below we analyze the code for the sort of topology:

public void Poto () {int orig_nverts = Nverts;//Record the number of vertices while (Nverts > 0) {//return vertices with no successor vertices int currentvertex = Nosuccessor S (); If no such vertex exists, return -1if (Currentvertex = =-1) {System.out.println ("Error:graph has cycles!"); return;} Sortedarray stores an ordered vertex (from the tail) sortedarray[nverts-1] = Vertexarray[currentvertex].label;deletevertex (CurrentVertex );//delete the vertex to facilitate the next loop, looking for the next vertex without a successor vertex}system.out.println ("topologically sorted Order:"); for (int i = 0; i < orig_nverts; i++) {System.out.print (sortedarray[i]);} System.out.println ("");}
The main work is done in the while loop, and the loop exits until the fixed-point number is 0 o'clock:
1. Call Nosuccessors () to find any vertex with no successor;

2. If a vertex is found, place the vertex in the Sortedarray array and delete the vertex;

3. If there is no such vertex, then the graph must exist in the ring.

At the end of the Sortedarray array, the vertices are stored in the sorted order. Below we analyze the Nosuccessor () method and the Deletevertes () method:

//return Vertex with no successorsprivate int nosuccessors () {boolean isedge;for (int row = 0; row < nverts; row++) {Isedge = Fal se;for (int col = 0; col < nverts; col++) {if (Adjmat[row][col] > 0) {//As long as the Adjmat array is stored in 1, indicating Row->colisedge = true;br Eak;}} if (!isedge) {//As long as there is an edge, return the last vertex to row;}} return-1;} private void Deletevertex (int delvertex) {if (Delvertex! = nVerts-1) {for (int i = Delvertex; i < nVerts-1; i++) {//del Ete from vertexarrayvertexarray[i] = vertexarray[i+1];} Delete the corresponding edge for in adjmat (int row = Delvertex; row < nVerts-1; row++) {//delete row from adjmatmoverowup (row, nverts);} for (int col = Delvertex; col < nVerts-1; col++) {//delete column from Adjmatmovecolleft (col, nVerts-1);}} nverts--;} 
As you can see from the code above, deleting a vertex is simple, removing it from the vertexarray and moving the vertices forward to fill the space. Similarly, the rows of vertices are removed from the adjacency matrix, and the row below and the right column move to fill the empty space. It's easier to delete the edges in the Adjmat array, and look at the methods of Moverowup and Movecolleft below:

private void moverowup (int row, int length) {for (int col = 0; col < length; col++) {Adjmat[row][col] = Adjmat[row+1][co L];}} private void Movecolleft (int col, int length) {for (int row = 0; row < length; row++) {Adjmat[row][col] = Adjmat[row][co L+1];}}
This introduces all the procedures for sorting the topology. The complete code is attached below:

Package graph;/** * Topological ordering of graphs: * Topological ordering is another operation that can be simulated with diagrams, which can be used to represent a situation in which certain items or events must be arranged or occur in a particular order. * The difference between the graph and the graph is that there is only one item in the adjacency matrix for the side of the graph. * The idea of topological sorting algorithm is unusual but simple, there are two steps required: * 1. Find a vertex with no successor * 2. Delete this vertex, insert the marker for the vertex in front of the list * Repeat these two steps until all vertices are deleted, and the order of the vertices displayed in the list is the result of topological ordering. * Deleting vertices appears to be an extreme step, but it is the core of the algorithm, and if the first vertex is not processed, the algorithm cannot calculate the second vertex to be processed. * If needed, you can store the graph's data (vertex list or adjacency matrix) elsewhere, and then restore them after the sort is complete.  * @author eson_15 * @date 2016-4-20 12:16:11 * */public class toposorted {private final int max_verts = 20;private Vertex Vertexarray[]; Stores the array of vertices private int adjmat[][]; A matrix array that stores whether there is a boundary, 0 means no bounds, and 1 indicates that there is a boundary private int nverts; Number of vertices private char sortedarray[]; An array of stored ordered data public toposorted () {Vertexarray = new Vertex[max_verts];adjmat = new Int[max_verts][max_verts];nverts = 0; for (int i = 0, i < max_verts; i++) {for (int j = 0; J < Max_verts; J + +) {Adjmat[i][j] = 0;}} Sortedarray = new Char[max_verts];} public void Addvertex (char lab) {vertexarray[nverts++] = new Vertex (Lab);} In the Addedge graph, there is only one public void in the adjacency matrix (int start, int end) {Adjmat[start][end] = 1;}public void Displayvertex (int v) {System.out.print (Vertexarray[v].label);} /* Topological sort */public void Poto () {int orig_nverts = Nverts;//remember how many vertswhile (Nverts > 0) {//get a vertex wi Th no successors or-1int Currentvertex = Nosuccessors (); if (Currentvertex = =-1) {System.out.println ("Error:graph has Cyc Les! "); return;} Insert vertex label in Sortedarray (start at end) sortedarray[nverts-1] = Vertexarray[currentvertex].label; Deletevertex (Currentvertex);} System.out.println ("topologically sorted Order:"); for (int i = 0; i < orig_nverts; i++) {System.out.print (sortedarray[i]);} System.out.println ("");} Return vertex with no successorsprivate int nosuccessors () {boolean isedge;for (int row = 0; row < nverts; row++) {IsE Dge = false;for (int col = 0; col < nverts; col++) {if (Adjmat[row][col] > 0) {Isedge = True;break;}} if (!isedge) {return row;}} return-1;} private void Deletevertex (int delvertex) {if (Delvertex! = nVerts-1) {for (int i = Delvertex; i < nVerts-1; i++) { Delete from vertexarrayvertexarray[i] = vertexarray[i+1];} for (int row = Delvertex; row < nVerts-1; row++) {//delete row from adjmatmoverowup (row, nverts);} for (int col = Delvertex; col < nVerts-1; col++) {//delete column from Adjmatmovecolleft (col, nVerts-1);}} nverts--;} private void moverowup (int row, int length) {for (int col = 0; col < length; col++) {Adjmat[row][col] = Adjmat[row+1][co L];}} private void Movecolleft (int col, int length) {for (int row = 0; row < length; row++) {Adjmat[row][col] = Adjmat[row][co L+1];}}}
Topological sort is introduced to this, if there is a mistake, welcome to the message ~

___________________________________________________________________________________________________________ __________________________________________

-----willing to share and progress together!

-----More articles please see: http://blog.csdn.net/eson_15

Topology sequencing of data structures and algorithm 17

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.