Deep search/Depth-first search/C ++

Source: Internet
Author: User

The figure is a common data structure. depth-first and breadth-first searches are common algorithms. This blog post first introduces deep-first searches.

As usual, I will introduce it in plain language, so I can understand it as long as I take it seriously. The presentation method will be introduced at the beginning. If you have mastered it, you can skip it.

Graph Representation

To represent a graph G (V, E), there are two common representation methods: the adjacent matrix and the adjacent table. These two methods can be used for Directed Graphs and undirected graphs. For a sparse chart, it is commonly represented by an adjacent table,

It occupies space | E | less than | V | * | V |.

Adjacent table:

The adjacent table of Figure G (V, E) is composed of an array (Adj) containing the V list. Each list corresponds to one vertex in V. For any vertex u in v, spiritual table Adj [u]

Contains all vertices that meet the condition (u, v) belong to E, that is, all vertices adjacent to u in the Adj [u.

Adjacent matrix:

In a matrix, the horizontal and vertical aspects of the matrix are arranged in an orderly manner. If the two points are connected by edges, the elements in the matrix are 1, and the opposite is 0.

You can understand the instance ~

For an undirected graph, the sum of the lengths of all adjacent tables is 2 | E |. For a directed graph, | E | (each edge of an undirected graph is expressed twice)

It has potential limitations. To determine whether an edge (u, v) exists, you can only search for v in the table Adj [u. If yes, yes, no.

In the graph G (V, E)'s Adjacent matrix representation method, assuming that a vertex numbers 1, 2, 3, and | V | according to a certain method, then G's Adjacent matrix is

| V | * | V | proof A = (aij), which satisfies the following requirements:

It occupies | V | * | V | space, regardless of the number of edges.

Deep Priority Search:

Deep priority search is to search for a graph as deep as possible. For a newly discovered node, if there is an edge that has not been detected from this start point, it will be detected along this edge.

After all the edges of vertex v are explored, the search will go back to those edges that find the starting point of vertex v. This process continues until it finds all points reachable from the origin.

If no vertex is found, select one of the seat Source Vertex and repeat the process.

Supplement:

1. You can record the access time of each point in this process.

Record the next time t_start at the access point, and record the time t_end when all neighbors are accessed at this point. Then the access time t = t_end-t_start.

The start and end times in the algorithm are described as d [u] and f [u].

2. Each time the depth first traversal is performed, the front node of the Access Node is recorded. An array f [I] can be used for storage. When the traversal is completed, the data in f [I] can be used to obtain the order of deep traversal. Its reverse order is

A topological sorting of this graph.

During the search process, you can color the vertex to indicate the vertex State. At the beginning, each vertex is white and is first dimmed during the search process,

It turns black at the end, that is, when other neighbors are located. D [u] and f [u] are used to record the start time and end time of the access.

Vertices initially colored white

Then colored gray when discovered

Then black when finished

D [u]: discovery time, a counter indicating when vertex u is discovered.

F [u]: finishing time, a counter indicating when the processing of vertex u (and the processing of all its descendants) is finished.

Algorithm Description:

In rows 1-3, all vertices are set to white, and in the third row, the parent node of each node is set to null. The fourth row sets the time count to 0. 5-7 rows query the vertices in v at a time. If they are white,

You call the DFS-VISIT to access the node. Each time a DFS-VISIT (u) is called, u becomes a root of the depth-first traversal.

The call DFS-VISIT (u) is, the start u is set to gray, the second line adds value to time, the third line records u Access start time d [u], 4-7 lines check u neighbor, if not

The access point, then the depth first traverses the point. Line 3: u becomes a dead node because it accesses all the neighbors of u, and sets the color of u to black. Line 3 records the end time of u access.

The depth-first traversal process can be expressed as follows:

 

The results of a deep-prioritized search may depend on the access order of each node in Row 5 of the DFS, or on the access order of the u neighbor in row 4th of the DFS-VISIT.

The following is the c ++ implementation:

View Code

/*
Depth Traversal
Source: A fish @ blog Park http://www.cnblogs.com/yanlingyin/
2011-12-26

*/
# Include <stdlib. h>
# Include <stdio. h>

Struct node/* graph vertex structure definition */
{
Int vertex;/* vertex data information */
Struct node * nextnode;/* indicates the indicator of the next vertex */
};
Typedef struct node * graph;/* New graph structure state */
Struct node head [9];/* graph vertex array */
Int visited [9];/* traverse the mark array */

/******************* Establish an adjacent table based on the existing information ************ ********/
Void creategraph (int node [20] [2], int num)/* num indicates the number of edges of the graph */
{
Graph newnode;/* pointer definition pointing to the new node */
Graph ptr;
Int from;/* edge start point */
Int to;/* Edge End */
Int I;
For (I = 0; I <num; I ++)/* read the edge information and insert the adjacent table */
{
From = node [I] [0];/* edge start point */
To = node [I] [1];/* Edge End Point */

/* Create a vertex */
Newnode = (graph) malloc (sizeof (struct node ));
Newnode-> vertex = to;/* Create vertex content */
Newnode-> nextnode = NULL;/* set the initial value of the indicator */
Ptr = & (head [from]);/* vertex position */
While (ptr-> nextnode! = NULL)/* traverse to the end of the linked list */
Ptr = ptr-> nextnode;/* Next vertex */
Ptr-> nextnode = newnode;/* Insert a node */
}
}

*********** *********/
Void dfs (int current)
{
Graph ptr;
Visited [current] = 1;/* records have been traversed */
Printf ("vertex [% d] \ n", current);/* output traversing vertex value */
Ptr = head [current]. nextnode;/* vertex position */
While (ptr! = NULL)/* traverse to the end of the linked list */
{
If (visited [ptr-> vertex] = 0)/* if it has not been traversed */
Dfs (ptr-> vertex);/* send back to traverse the call */
Ptr = ptr-> nextnode;/* Next vertex */
}
}

******* ***********************/
Int main ()
{
Graph ptr;
Int node [20] [2] = {1, 2}, {2, 1},/* edge array */
{1, 3}, {3, 1 },
{1, 4}, {4, 1 },
{2, 5}, {5, 2 },
{2, 6}, {6, 2 },
{3, 7}, {7, 3 },
{4, 7}, {4, 4 },
{5, 8}, {8, 5 },
{6, 7}, {7, 6 },
{7, 8}, {8, 7 }};
Int I;
// Clrscr ();
For (I = 1; I <= 8; I ++)/* vertex array initialization */
{
Head [I]. vertex = I;/* set the vertex value */
Head [I]. nextnode = NULL;/* the pointer is NULL */
Visited [I] = 0;/* set the traversal initial flag */
}
Creategraph (node, 20);/* Create an adjacent table */
Printf ("Content of the gragh's ADlist is: \ n ");
For (I = 1; I <= 8; I ++)
{
Printf ("vertex % d->", head [I]. vertex);/* vertex value */
Ptr = head [I]. nextnode;/* vertex position */
While (ptr! = NULL)/* traverse to the end of the linked list */
{
Printf ("% d", ptr-> vertex);/* print vertex content */
Ptr = ptr-> nextnode;/* Next vertex */
}
Printf ("\ n");/* line feed */
}
Printf ("\ nThe end of the dfs are: \ n ");
Dfs (1);/* print the output traversal process */
Printf ("\ n");/* line feed */
Puts ("Press any key to quit ...");
// Getch ();
}

The above code is compiled on cfree5.

 

 

 

 

The depth-first search of the image can be implemented by using stacks. For A certain layer of points, such as A, B, and C, they are all put into the stack. Every time the child of the top element of the stack is put into the stack, when there is no child at a certain point,

Roll back to the node with a child, put its child into the stack, and repeat the process until every child on the Root Node enters the stack, the final order of the output stack is the order of depth-first traversal.

Correspondingly, the breadth-first search is implemented by queue. For A layer of vertices A, B, and C, put them in the queue, and then the queue header is in the queue, and the right child is in the queue, if A has children M, N

In this case, the queue after queue A is bcen, and the next step is B's outgoing queue. The order of the Child B's incoming queues, and outgoing queues is the order of the breadth-first traversal.

The next article will introduce the breadth-first search algorithm ~

 

References: Algorithms

Http://en.wikipedia.org/wiki/Depth-first_search

If there is reprint please indicate the source: http://www.cnblogs.com/yanlingyin/

A fish @ blog

2011-12-26

 

 

 

 

 

 

 

 

 

 

 

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.