The traversal of graphs

Source: Internet
Author: User

The traversal of the graph is similar to the traversal of a tree, where one vertex is expected to go through the remaining vertices of the graph and make each vertex accessible only once, a process called graph traversal. For the traversal of graphs, how to avoid the loop of loops, we need to design the ergodic scheme scientifically, through two kinds of traversal order scheme: depth-first traversal and breadth-first traversal. 1. Depth-First traversal      Depth-first traversal, also known as depth-first search, referred to as DFS. In fact, it's like a tree's pre-sequence traversal.       It starts at a node V, accesses this 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.       the way we use adjacency matrices, the code looks like this.    #define Maxvex  100     //maximum vertex number typedef int Boolean;            //boolean is a Boolean type whose value is True or Falseboolean visited[ Maxvex];        //Access Flag Array # define TRUE 1#define FALSE 0 //adjacency matrix Depth-first recursive algorithm void DFS (Graph g , int i) {    int j;    visited[i] = true;    printf ("%c ", G.vexs[i]);                            //print vertices, or other operations     for (j = 0; J < g.numvertexes; J + +)     {        if (G.arc[i][j] = = 1 &&!visited[j])          {             DFS (G, J);                  // Call         }    }} //on the adjacency vertex recursively for access Depth traversal of adjacency matrix operation Void Dfstraverse (Graph g) {    int i;    for (i = 0; i < g.numvertexes; i++)     {        visited[i] = FALSE;          //initialization all vertex states are non-visited states     }    for (i = 0; i < g.numvertexes; i++)     {        if (!visited[i])              //calls Dfs on an unreachable vertex, and if connected graph, only executes once &NBSP;&Nbsp;      {             dfs (g,i);         }    }}-------------------- ---------------------------  If you are using an adjacency table storage structure, the code for the Dfstraverse function is almost the same, except in the recursive function because the array is replaced by a linked list, the code is as follows. Depth recursive algorithm for  //adjacency table void DFS (graphlist g, int i) {    edgenode *p;    visited[ I] = true;    printf ("%c", g->adjlist[i].data);   //print vertices, or other operations     p = G->adjlist[i].firstedge;    while (P )     {        if (!visited[p->adjvex])          {             dfs (g, P->adjvex);           //neighbor Vertex recursive call to access          }   &Nbsp;    p = deep traversal of p->next;    }} //adjacency table operation void DFSTraverse ( Graphlist g) {    int i;    for (i = 0; i < g.numvertexes; i++)   & Nbsp; {        visited[i] = false;    }     for (i = 0; i < g.numvertexes; i++)     {         if (!visited[i])         {             dfs (g, i);        }     }}      compared with the depth-first traversal algorithm of two different storage structures, the adjacency matrix is composed of a two-dimensional array for the graph of n vertex e bars. To find the adjacency point of a vertex requires access to all elements in the matrix, because O (N2) time is required. When the adjacency table is the storage structure, the time required to find the adjacency point depends on the number of vertices and edges, so it is O (n+e). It is obvious that the adjacency table structure makes the algorithm greatly improve the time efficiency for sparse graphs with few points.  -------------------------------------------------------------------------------------  2. Breadth-First traversal       breadth-first traversal, also known as breadth-first search, referred to as BFS. The breadth-first traversal of a graph is similar to a tree's sequence traversal. When the       adjacency matrix does the storage structure, the breadth-first search code is as follows. The breadth traversal algorithm of  //adjacency matrix is void Bfstraverse (Graph g) {    int I, j;    queue Q;     for (i = 0; i < g.numvertexes; i++)     {         visited[i] = False;    }    initqueue (&q);     for (i = 0; i < g.numvertexes; i++)//loop     {     for each vertex     if (!visited[i])                //If you have not visited         {             visited[i] = true;             printf ("%c", G.vexs[i]); Print nodes, or other operations              enqueue (&q, i);           //this node into the queue              while (! Queueempty (q))     //the elements out of the queue, assigning them to              {                 int m;                 DeQueue (&q, &m);                 for (j = 0; J < G.numvertexes; J + +)                  {                     //determine if the other vertices have edges with the current vertex and have not visited               &nbSp;      if (G.arc[m][j] = = 1 &&!visited[j])                      {                       &NBSP;&NBSP;&NBSP;VISITED[J] = true;                         printf ("%c", G.vexs[j]);                          enqueue (&q, J);                     }                 }             }        }    }}   1 ---------------------- --------------------  for the breadth-first traversal of adjacency tables, the code differs little from the adjacency matrix and the code is as follows. Breadth traversal algorithm for  //adjacency table void Bfstraverse (Graphlist g) {    int I;    edgenode *p;     queue q;    for (i = 0; i < g.numvertexes; i++)      {        visited[i] = false;    }     initqueue (&AMP;Q);     for (i = 0; i < g.numvertexes; i++)     {         if (!visited[i])         {             visited[i] = TRUE;             printf ("%c", g.adjlist[i].data);   //print vertices, or other operations              enqueue (&q, i);             while (! Queueempty (q))             {                 int m;                 dequeue (&q, &m);                 p = G.adjList[m].firstedge;      find the current vertex edge table header pointer                  while (P)                  {                     if (!visited[p->adjvex])                      {                         visited[p-> Adjvex] = true;                         printf ("%c", G.adjlist[p->adjvex].data);                          enqueue (&q, P->adjvex);                     }                     p = p->next;                 }             }        }    }}   The depth-first traversal and breadth-first traversal algorithms of    contrast graphs show that they are the same in time complexity, except that the order of access to vertices is different.   can be seen in the full graph traversal is no good or bad points, but different circumstances choose different algorithms.

Traversal of the graph

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.