Brief introduction
Graph represents the relationship between points, in C # by the set of node objects to represent the point (Vertex), with the adjacency matrix (adjacency) to represent the relationship between the points. Here's a C # implementation.
PS: This article is my review of notes, code comments are very complete. Don't spit the groove.
Object that represents the point
The following implementation code:
Class Vertex
{
publicstring Data;
Publicbool isvisited;
Public Vertex (String vertexdata)
{
Data = vertexdata;
}
}
Each node contains two fields, which are node data and a Boolean type that represents whether it has been accessed.
Object representing the diagram
In addition to the set of points and the adjacency matrix, some basic methods of adding or removing elements to the diagram and a construction method to initialize the graph are needed.
Publicclass Graph {//graph can contain the point cap privateconstint number = 10;
Vertex array private vertex[] vertiexes;
Adjacency Matrix publicint[,] adjmatrix;
Statistics the current figure has several points int numverts = 0;
Initialize Graph public graph () {//Initialize adjacency matrix and vertex array Adjmatrix = new int32[number, number];
Vertiexes = new Vertex[number];
Initialize all tables representing the adjacency matrix to 0for (int i = 0; i < number; i++) {for (int j = 0; J < number; J +)
{adjmatrix[i, j] = 0; Add a node to the diagram Publicvoid Addvertex (String v) {Vertiexes[numverts] = NE
W Vertex (v);
numverts++;
}//To add a forward edge publicvoid Addedge (int vertex1, int vertex2) {adjmatrix[vertex1, vertex2] = 1;
Adjmatrix[vertex2, vertex1] = 1; }//Display point publicvoid displayvert (int vertexposition) {Console.WriteLine (vertiexes[vertexposition]+ ""); }
}
Topology Sorting (Topsort)
A topological sort is linearized for all vertices in a graph that has a direction and is not a loop. Several steps are required
1. First, no successor nodes are found.
2. Add this node to the linear stack
3. Delete this node in the diagram
4. Repeat steps 1,2,3
Therefore, you first need to find the successor node method:
To find the point//specific representation of no successor node in the graph is
that a column in the adjacency matrix is all 0//at this time the line number is returned if no return -1privateint findnosuccessor ()
{
bool Isedge is found;
Loop line for (int i = 0; i < numverts; i++)
{
Isedge = false;
Loop column, there is a 1 jump out of the loop for (int j = 0; J < Numverts; J + +)
{
if (adjmatrix[i, j] = = 1)
{
Isedge = true;
break;
}
}
if (!isedge)
{return
i;
}
}
return-1;
}