Data structure-Graph traversal __ Data structure

Source: Internet
Author: User
Traversal of graphs

Graph traversal (traversing graph): from one vertex of the graph, visit the remaining vertices in the diagram, and each vertex is only accessed once.
The traversal algorithm of graphs is the basis of operation of various graphs. However, the traversal of the diagram has the following characteristics:
Complexity: Any vertex of the graph may be adjacent to the rest of the vertices, possibly after a certain vertex has been accessed and then returned to the original vertex, while some of the vertices have not been traversed.
Workaround: Note the vertices that have been accessed during the traversal process. Set an auxiliary vector VISITED1...N, its initial value is 0, once the vertex vi is accessed, make visited[i] 1 or the order number of the access.
The traversal algorithm of graph has depth first search algorithm and breadth first search algorithm. Depth Priority search (Depth first Search–dfs)

Depth-First search (Depth first Search–dfs) traverses a tree-like sequence traversal, which is the generalization of a tree's first-order traversal.
1 algorithm thought
When the initial state is set, all vertices in the diagram are not accessed:
⑴: Starting from a vertex vi in the graph, accessing VI, and then finding an adjacent vertex vi1 of VI;
⑵: From VI1, Depth-first search access and vi1 all vertices adjacent to and not accessed;
⑶: Turn ⑴ until all vertices adjacent to VI are accessed
⑷: Continue to select the vertex VJ as the starting vertex, and go (1) until all vertices in the diagram are accessed.
Algorithm Implementation
Known by the algorithm, this is a recursive process. Therefore, the first design of a vertex (number) for V0 start Depth first search function, easy to invoke.
When you traverse the entire diagram, you can perform the defined function on each of the unreachable vertices in the diagram.

typedef  EMNU {FALSE, TRUE} BOOLEAN;
BOOLEAN  Visited[max_vex];
3  node and its type definition
#define MAX_VEX              /*  max vertex number
/typedef char VERTEXTYPE;/* Vertex type should be defined
by user/* typedef int EDGETYPE;      /* Side of the weight value type should be defined by the user


/typedef struct EDGENODE  /* Side table node
    /{int adjvex;    /* Adjacent point domain, store the vertex corresponding subscript
    /edgetype info;   /* For the storage weight, for non-network map can not need
    /* struct Edgenode *next/* chain domain, point to the next adjacent point * *
}edgenode;
typedef struct VERTEXNODE/* Vertex table node *
    /{vertextype data;          /* Vertex domain, storage vertex information * * *  int  indegree;    The degree of the vertex, the direction of the graph is the degree or the degree       (also not) * *
    edgenode *firstarc;   * * Side Table Head pointer * * *
}vertexnode, Adjlist[max_vex];

typedef struct
{
    adjlist adjlist;  The vertex array (also becomes the head node vector)
    int numnodes,numedges;/* The current vertex number and the number of edges in the graph * *
}graphadjlist;
void  DFS (graphadjlist *gl, int v)
{     Edgenode *p;
Visited[v]=true; 
VISIT[V];       /* Set  access flag, access vertex v/  * 
p=gl->adjlist[v].firstarc;   /*  The first node of the linked list */while
(p!=null)
{  if  (! Visited[p->adjvex]) 
    DFS (GL, P->adjvex);//Call
    P=p->next
by recursion from the unreachable adjacency vertex of V} void Dfstraverse (Graphadjlist *gl)
{       int v;
        for (v=0; v<gl->vexnum; v++)
        visited[v]=false;  /* Access flag initialization  /for 
        (v=0 v<gl->vexnum; v++)
            if (! VISITED[V])   
                DFS (GL, v);
}

3 Algorithm Analysis
When the adjacency table is used as the storage structure traversal, the time required to find the adjacency point depends on the number of vertices and edges, and the total time complexity is O (n+e).

A depth-first recursive algorithm with adjacency matrix
void DFS (mgraph G, int i)
{   int J;
    Visited[i] = TRUE;
    VISIT[V]; 
    for (j = 0; J < G.numvertexes; j)
        if (g.arc[i][j] = = 1 &&!visited[j])
            DFS (G, J); 8/>}
void Dfstraverse (mgraph G)
{   int i;
    for (i = 0; i < g.numvertexes; i++)
         visited[i] = FALSE;/* Initial all vertex states are not accessed state *
    /for (i = 0; i < g.numvertexes ; i++)
         if (!visited[i])//DFS is invoked on a vertex that is not accessed, only one
        dfs (G, i) is executed once on the connected graph;

Breadth Priority search (breadth first search–bfs)

Breadth-First search (breadth-SEARCH–BFS) traverses a hierarchical traversal of similar trees.
1 algorithm thought
When the initial state is set, all vertices in the diagram are not accessed:
⑴: From the graph of a vertex VI, Access VI;
⑵: Access all vertex vi1,vi2,...,vim that are adjacent to VI and not accessed;
⑶: To Vi1,vi2, ..., the order of Vim, Vij (1≦j≦m) in turn as VI, turn ⑴;
⑷: Continue to select the vertex VK as the starting vertex and turn ⑴ until all vertices in the diagram are accessed.
2 algorithm implementation
An array of Access tokens is also required in order to mark whether a vertex has been accessed in the graph;
When accessing VI, in order to access each vertex adjacent to VI in turn, a queue is needed to hold the vertices adjacent to VI.

bool Visited[max_vex]; typedef struct QUEUE {int elem[max_vex]; int front, rear;}     Queue; /* Define a queue save will access vertex */
void bfstraverse (graphadjlist *g) {Establish an empty queue and initialize (q->front=q->rear=0) Access flag initialization
                (visited[i]=false,0≤i< g->vexnum) for (i=0; i<g->vexnum; i++) {if (!visited[i)) 
                     {visited[i]=true; The vertex is accessed, and then the vertex is queued, while (!).
                Queueempty (Q)) {dequeue (&q,&i); p = gl->adjlist[i].firstedge; Locate the edge of the current vertex pointer while (p) {if (!visited[p->adjvex])/* If this vertex is not accessed/{visited[p
                ->adjvex]=true; access to the vertex; then the vertex is queued}//end of If p = P->nex    T /* The pointer points to the next adjacent point/}//end of While}}} 

The breadth-first search algorithm and the depth-first search algorithm are the same in time complexity, except that the vertex access order is different.
The traversal of graphs can systematically access each vertex in the graph, therefore, the traversal algorithm of graphs is the most basic and most important algorithm, many of the operations of the graph are based on the traversal of the graph to achieve the change. minimum Spanning Tree

If the connected graph is a weighted graph, the edges in the spanning tree are also weighted, and the sum of the weights of all the edges in the tree is called the cost of the spanning tree.
Minimum spanning tree (Minimum spanning): the least expensive spanning tree in a weighted connected graph is called the minimum spanning tree.
There are many algorithms for constructing the minimum spanning tree, the most classic of which are two kinds:
Primm (Prim) algorithm
Kruskal (Kruskal) algorithm Primm (Prim) algorithm

    Find the smallest spanning tree t= (U,te) from the Connected network n= (u,e).
1 The algorithm thought
⑴  if constructs from the vertex v0, u={v0},te={};
⑵ first find the Edge (u,v) with the smallest weight value, U∈u and v∈v-u, and the child graph does not form a ring, then u= u∪{v},te=te∪{(U,V)};
⑶ repeat ⑵ until u=v. Then the TE must have n-1 edges, and t= (U,te) is the smallest spanning tree.

2 Algorithm Implementation Instructions
An adjacency matrix (two-dimensional array) is used to represent the graph, and the weight of the nonexistent edges between the two vertices is the maximum allowable value of the machine.
To facilitate the implementation of the algorithm, a one-dimensional array closedge[n] is set up to hold the vertices in the v-u with the least weighted value of the vertices in the U. The type definition of an array element is

struct {int adjvex;    /* The least weighted edge is attached to the vertex/int lowcost in U;
* * The value of the edge/}closedge[max_edge]; 
       For example: Closedge[j].adjvex=k, indicating that the edge (VJ, VK) is the smallest edge in the v-u vertex VJ to u, and vertex VK is the vertex of the U in which the edge is attached.
Closedge[j].lowcost the weight that is stored on the edge. 
        In the prime algorithm, the graph uses the adjacency matrix to store, the minimal spanning tree that constructs uses the one-dimensional array to store its n-1 strip edge, each edge's storage structure describes: typedef struct Mstedge {int vex1, vex2;     /* Side of the graph attached to the two vertices/weighttype weight;
/* Side of the weight of * *}mstedge;
                                 Algorithm implementation (abbreviated) #define INFINITY max_val/* Max/Mstedge *prim_mst (adjgraph *g, int u)  * * to construct the minimum spanning tree of graph G/{Mstedge te[] from the first U vertex;
          The array pointer int J, K, V, Min, which holds the n-1 bar of the minimum spanning tree;
            For (j=0 j<g->vexnum; j + +) {closedge[j].adjvex=u; 
        CLOSEDGE[J].LOWCOST=G-&GT;ADJ[J][U]/* Initialize array closedge[n] */      closedge[u].lowcost=0;
/* Initial Time U={u} * * te= (Mstedge *) malloc (g->vexnum-1) *sizeof (Mstedge));
  For (j=0 j<g->vexnum-1; j + +) {min= INFINITY; For (v=0 v<g->vexnum; v++) if (closedge[v].lowcost!=0&& closedge[v).  Lowcost<min) {min=closedge[v].lowcost; k=v; } TE[J].VEx1=closedge[k].adjvex;
                         Te[j].vex2=k;
                         Te[j].weight=closedge[k].lowcost;      closedge[k].lowcost=0; /* Add vertex k to u medium */for (v=0 v<g->vexnum; v++) if (g->adj[ V][K]&LT;CLOSEDGE[V].
                                    Lowcost) {closedge[v].lowcost= g->adj[v][k]; 
                                 Closedge[v].adjvex=k;
}/* Modify the values of each element of the array Closedge[n]//return (TE); 
 }/* Prime algorithm for minimum spanning tree * *
Kruskal (Kruskal) algorithm

1 algorithm thought
Algorithm idea: Set up connected network n= (v,e), make minimum spanning tree
The initial state is a non-connected graph t= (V,) with only n vertices, each vertex being a connected component
Select the least expensive edge in E, and add the edge to T if the vertex attached to it falls on a different connected component in t; otherwise, take this side and pick the next least expensive edge.
And so on, until all vertices in t are on the same connected component
2 Algorithm Implementation Instructions
The key to the implementation of the Kruskal algorithm is: When an edge is added to the set of te, how does it determine whether the loop is formed?
Workaround: Define a one-dimensional array vset[n] that holds the number of the connected components of each vertex in the diagram T.
Vset[n]:
Initial value: Vset[i]=i, which means that each vertex is composed of a connected component, and the number of connected components simply uses the position (number) of the vertex in the diagram.
When adding an edge to T (VI,VJ), check the vset[i] and Vset[j] values:
☆ If VSET[I]=VSET[J]: it is shown that VI and VJ are in the same connected component, and joining this side will form a loop;
☆ If VSET[I]≠VSET[J], the addition of this edge does not form a loop, adding this edge to the edge set of the spanning tree.
After a new edge is added, two different connected components are merged: The number of one connected component is replaced by the number of the other connected component.

Algorithm analysis: Set with the right connected graph has n vertices, e edge, the main implementation of the algorithm is:
Vset Array Initialization: Time complexity is O (n);
The side table is sorted by weight: If the heap is sorted or sorted quickly, the time complexity is O (e㏒e);
While loop: the maximum execution frequency is O (n), which contains a modified Vset array, a total of n-1 times, and a time complexity of O (N2);
The time complexity of the whole algorithm is O (e㏒e+n2).

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.