Data structures and algorithms: graphs

Source: Internet
Author: User

Graph theory is an important branch of computer research, the content of graph theory can be written a lot, but precisely because of the complexity of the graph theory, in the programmer interview written examination, the problem of graph theory is not very rare, the investigation is not abstruse. This section covers some of the frequently occurring graph theory questions and gives detailed answers.

    • Topological sorting
    • DFS BFS
      • Dfs
      • BFS
    • Critical path
    • Shortest path

Topological sorting

From the point of view of mathematics, topological ordering is the operation of a partial order relation on any set to get the whole order relation of the set. If all the elements in a collection are used as nodes of the graph, and the partial order relationship on the set is used as the edge of the graph, then any one of the partial order relationships can represent a forward graph.

Topological ordering is an important operation of a forward graph. In a given graph G, if the vertex sequence is v1,v2, ..., the VN satisfies the following conditions: if there is a path from Vertex VI to VJ in the direction graph G, then the vertex VI must be called a topological sequence before the vertex VJ in the sequence. The process of finding an encounter topology sequence is called topological ordering.

The topological ordering of a graph can be seen as a sequence of all the vertices in the graph arranged along the horizontal line, so that all the forward edges are pointed from left to right. In many applications, a non-circular graph is used to illustrate the sequence in which events occur.

The common topology ordering method is as follows:
(1) Select a vertex with no precursor (that is, 0) from the graph and output it.
(2) by deleting the vertex and deleting all edges emitted from the vertex.
(3) Repeat the above steps (1) and step (2) until there are no vertices with no precursor nodes in the current graph, or until all the nodes in the current graph are output.

It is important to note that a topological sort sequence with a forward-free graph is not unique .

For example, for figure 13-20, a topological sort would get two sequences: {v1,v2,v5,v4,v3,v7,v6} or {v1,v2,v5,v4,v7,v3,v6}

The algorithm of sorting from topology shows that if the AOV network has n vertices, e edges, in the process of topological sorting, searching for vertices with zero degree, the time required to build the vertex stack is O (n). Under normal circumstances, there are n vertices to the graph, each vertex into the stack, out of the stack, output a total of n times. The operation of vertex-to-degree minus 1 is performed in total e-times. Therefore, the total time complexity of topological sorting is O (n+e).

Dfs? BFS

The most common way to traverse a graph is to have a depth-first traversal (Depth-first Search,dfs) and a breadth-priority traversal (breadth-Search, BFS). The depth-first algorithm of graphs is similar to the root traversal of trees, and the breadth-first algorithm of graphs is similar to the hierarchical traversal of trees.

Dfs

DFS is a depth-first traversal that starts at each vertex, and the result is that the branch path is traversed deeply to no further depth, and each vertex can only be accessed once. The implementation process is triggered from a vertex v in Figure G, the node is accessed first, and then a depth-first traversal is performed along the adjacent vertex of the non-visited v until the other vertices with a connected path between the figure G and the vertex v are accessed. At this point, if there are other vertices in figure g that have not been accessed, choose one of these vertices as the starting vertex, repeating the process until all the vertices in Figure g have been accessed.

The specific implementation code for the depth-first search algorithm is as follows:

intVisited[n];//Array visited[] represents the access of vertices in the graph, 1 means access, 0 means no accessvoidDFS (Graph G,intV) {Visited[v] =1; Visit (v);//indicates access to vertex v    //function Firstadjvex (G,V) returns the first adjacency point of V in Figure G    //function Nextadjvex (g,v,w) returns the next adjacency vertex (relative to W) of V in Figure G, or null if W is the last adjacency point of v     for(W=firstadjvex (g,v); w>=0; W=nextadjvex (g,v,w)) {if(!visited[w]) DFS (G,W);Depth-First search for non-visited adjacency vertices of v}}voidDfssearch (Graph G)//Depth-first search for figure G{ for(v=0;v<g.vexnum; ++V) Visited[v] =0; for(v=0;v<g.vexnum; ++V)if(!visited[v]) DFS (G,V);//Call DFS for vertices that have not been visited}
BFS

BFS, also known as the width-first algorithm, belongs to a blind search method and is a very important prototype of the graph algorithm. The goal is to search all the vertices in the graph layer by level and ensure that all vertices in the diagram are accessed only once.

The process is as follows: In the given figure g= (V,e), from a vertex v in Figure G, after accessing the vertex, access all the adjacent vertices of the non-visited V, then proceed along these vertices, and then access the adjacent vertices that they have not been visited, It is guaranteed that the adjacent vertex of the vertex being accessed first is accessed before the adjacent vertex of the vertex being accessed. After all vertices with a connecting path to vertex v are accessed, if there are other vertices in figure g that have not been accessed, select one vertex from the vertices as the starting vertex and repeat the process until all the vertices in Figure g have been accessed.

The specific implementation code for the breadth-first search algorithm is as follows:

intVisited[n];//indicates access to the vertex, 1 indicates access, 0 indicates no accessvoidBfssearch (Graph G) { for(v=0; v<g.vexnum; ++V) Visited[v] =0; Initqueue (Q)//Initialize queue     for(v=0; v<g.vexnum; ++V)if(!visited[v]) {Visited[v] =1;            Visit (v); EnQueue (Q,V); while( ! Queueempty (Q)) {Dequeue (q,u);//OUT Team                 for(W=firstadjvex (g,u); w>=0; W=nextadjvex (G,U,W))if(!visited[w]) {Visited[w] =1;                        Visit (w);                    EnQueue (Q,W); }            }        }}
Critical path

A critical path is the path of the longest length in a graph (AOE) (the sum of the time that each activity on the path lasts).
Use E (k) to indicate the earliest start time of an activity (that is, ARC) K
Using L (k) to indicate the latest start time of the activity K, the activity of e (k) = L (k) is called the key activity. All activities on the critical path are key activities.
Since some activities in the AOE network can be carried out simultaneously, the time required to complete the project should be the maximum path length from the beginning to the end point. The critical path length is the shortest duration required for the entire project.

Use ve (i) to denote the earliest start time of the event (that is, vertex) I, and VL (i) represents the late start of event I. If the activity k is represented by an arc <m,n> , the duration of the activity is indicated by the DUT:

e(k) = ve(m)l(k)=vl(n)-dut(<m,n>)

The specific algorithm for solving the critical path is as follows (assuming that the graph has n vertices):
(1) From the beginning vertex v0, assume that ve (0) = 0, and then according to the topological order to find the other vertex I of the earliest start time ve (i), if the resulting topological sequence of vertices less than the number of vertices in the graph, then there is a loop in the diagram, the algorithm ends, otherwise continue to execute.
(2) Starting from the end of the vertex vn, assuming v1 (n-1) =ve (n-1), and then according to the topological order to find the other vertex i the latest occurrence of VL (i)
(3) According to the earliest start time of each vertex ve (i) and the latest start time VL (i) in turn to find out the earliest start time of each arc e (k) and the latest start time L (k), if there is e (k) =l (k), is a key activity. The path to the key activity is the critical path.

Shortest path

Dijkstra algorithm principle is for the source vertex v0, first select its directly adjacent vertices in the shortest length of the vertex VI, then according to known, from the V0 through VI to reach the apex of the vi directly adjacent to the vertex VJ the shortest distance dist[j] and matrix[v0][j MATRIX[I][J] minimum value, i.e. dist[j]=min{matrix[v0][j], Dist[i]+matrix[i][j]}

The implementation of the algorithm is as follows (S is the endpoint set for the shortest path, and V is the collection of all nodes)
(1) V-s = The set of vertices for which the shortest path is not determined, the initial s={a}, and the absence of an edge between two nodes means that the path length between the two points is infinitely large
(2) The next path is calculated: First, the middle of a to VI only through the vertex of the shortest path, wherein, vi belongs to V-S. Then, the shortest path is compared with the source point A to the path length of the node vi, the minimum length is the shortest path from source point A to Node VI. Finally, the end of the shortest path (i.e. VI) is added to the S
(3) Repeat step (2) until the shortest path of all endpoints is found, that is, the number of nodes in S is equal to the number of nodes in V.

The time complexity of the Dijkstra algorithm is O (n^2), the spatial complexity depends on the storage mode, the adjacency matrix is O (n^2)

In addition to the Dijkstra algorithm, the Bellman-ford algorithm is also a common algorithm for solving single-source shortest path problem. Unlike the Dijkstra algorithm, in the Bellman-ford algorithm, the weight of the edge can be negative, its timeliness is better, the time complexity of O (VE)

Data structures and algorithms: graphs

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.