Graph algorithm--realization and application of Shortest path algorithm

Source: Internet
Author: User
Shortest path

In solving the problem of network routing, it is very important to find the shortest path or the least weighted path of one vertex to another in the graph.

It is formally stated that given a weighted graph g= (v,e), the shortest path to vertex T in the vertex s to V is the least expensive path to connect s to T in the set S in the E-side.

When S is found, we solve the single-pair vertex shortest path problem. To achieve this, in fact, the first to solve the more general single-source shortest path problem, single-source shortest path problem is to solve the single-vertex shortest path part of the process. In the single source shortest path problem, the shortest path from one vertex s to the other adjacent vertices is computed. This is the way to solve this problem because there is no better way to solve the single-pair vertex shortest path problem.

Dijkstra algorithm

One of the methods to solve the single-source shortest path problem is the Dijkstra algorithm.

The Dijkstra algorithm generates a shortest path tree whose root is the starting vertex s, and the branch of the tree is the shortest path from vertex s to all other vertices in Figure G . This algorithm requires that all weights in the graph are non-negative. Like the prim algorithm, the Dijkstra algorithm is also an algorithm that uses greedy algorithms to calculate and ultimately produce optimal results.

fundamentally, the Dijkstra algorithm determines whether the shortest path of each vertex is optimal, by selecting a vertex and continually exploring the edges associated with this vertex . This algorithm is similar to the breadth-first search algorithm, because it is the first to traverse all the vertices related to this vertex before the deeper vertices in the diagram are explored. In order to calculate the shortest path before s and all other vertices, the Dijkstra algorithm needs to maintain the color value and shortest path estimation for each vertex. Typically, the shortest path estimate is represented by the variable d.

Start by setting all the color values to white, the shortest path estimation is set to ∞ (representing a large enough number, which is greater than the weights for all edges in the graph). Set the shortest path estimate for the starting vertex to 0. As the algorithm evolves, a parent node is assigned to each vertex (except the starting vertex) in the shortest path tree. The parent node of the vertex may change several times before the algorithm ends.

The Dijkstra algorithm runs as follows:

first, between all the white vertices in the graph, select the vertex u with the smallest shortest path estimate. Initially, the shortest path estimate is set to 0 for the vertex to be the starting vertex. When this vertex is selected, it is painted black.

Then , for each vertex v adjacent to U, release its edge (U,V). When we release the edge, we want to confirm whether we want to update the shortest path computed so far. The method is to add the weights of (u,v) to the shortest path estimation of U. If the total value is less than or equal to the shortest path estimate for V, the value is assigned to V as the new shortest path estimate for V. also, set U to the parent node of v .

Repeat the process until all the vertices are marked black. Once the shortest path tree has been computed, the shortest path from S to another vertex T can be determined uniquely: from the node at T in the tree to the subsequent parent node until it reaches S. The reverse path for this lookup path is the shortest path from S to T.

Shows the calculation process for the shortest path from a to other vertices in the graph. For example, the shortest path from A to B is (a,c,f,b), with a weight of 7. The shortest path estimation and the parent node of each vertex are displayed next to each vertex. The shortest path estimate appears on the left side of the slash, and the parent node appears to the right of the slash. The light gray Edge is the edge of the shortest path tree growth process.

Interface definition for Shortest path

Shortest

int shortest (Graph *graph, const Pathvertex *start, List *paths, int (*match) (const void *key1, const void *key2));

return value : returns 0 if the shortest path is calculated, otherwise 1.

description : Used to calculate the shortest path between the vertex start and all other vertices in the weighted graph graph. This changes the graph, so if necessary, make a backup of the diagram before calling this operation.

Each vertex in graph must contain data of type Pathvertex. By setting the value of the member weight in the Pathvertex struct to specify the weight of each edge, the value of weitht is determined by the parameter data2 the incoming Graph_ins_edge. Use the member data of the Pathvertex struct to hold vertex-related data, such as the identifier of the vertex.

The match function of graph (called when the function is initialized with Graph_init) is used to compare data members in the Pathvertex struct. This function is the same as the parameter match in the incoming shortest.

Once the calculation is complete, the information about the shortest path will be returned to Paths,paths as a list of stored Pathvertex structures. In paths, the parent node of the starting vertex is set to null. The parents member of each of the other vertices points to the vertex that precedes the vertex, which is above the shortest path starting at the starting vertex. The vertices in the paths point to the actual vertices in graph, so as long as the paths can be accessed, the function call must ensure that the memory space in graph is valid. Once you no longer use paths, call List_destroy to destroy the paths.

complexity : O (EV2), where V is the number of vertices in the graph, and E is the number of entries in the edge.

The realization and analysis of shortest path

To calculate the shortest path to a vertex to all other vertices in a weighted graph, the graph is represented in the same way as in the smallest spanning tree. Just replace the vertex Mstvertex structure with the PATHVERTEX structure.

Pathvertex is capable of representing a tree graph while being able to track the information needed by the Dijkstra algorithm for vertices and edges. This struct contains 5 members: Data is a vertex-dependent, weight is the weight of the edge to which the vertex is reached; color is the colour of the vertex; D is the shortest path estimate of the vertex; the parent is the right kind point of the vertex in the shortest path.

The process of constructing a diagram containing a pathvertex struct is the same as constructing a diagram that contains a mstvertex struct body.

The shortest operation first initializes each vertex in the adjacency table structure list. The shortest path estimate for each vertex is initialized to Dbl_max (except for the starting vertex, the initial value of the starting vertex is 0.0). Maintains vertex color values, shortest path estimates, and parent nodes with vertices stored in the list of adjacent table structures. The reason is the same as the interpretation of the minimum spanning tree.

the core of the Dijkstra algorithm is to iterate over each node in the diagram with a single loop . In each iteration, the shortest path is first selected in the selected white vertex to estimate the smallest vertex . At the same time, this vertex is blacked out in the adjacency table structure list. Next, traverse the vertices adjacent to the selected vertex . when iterating through each vertex, check its color and shortest path estimation in the list of adjacency table structures. Once this information is obtained, call relax to release the edges between the selected vertices and the adjacent vertices. If you find that you need to update the shortest path estimates and parent nodes of adjacent vertices in this procedure, update this vertex in the list of adjacency table structures. Repeat the process until all the vertices are painted black.

once the main loop in the Dijkstra algorithm ends, the process of calculating the shortest path from the starting vertex to all other vertices in the graph is completed. At this point, each black Pathvertex structure in the list of contiguous table structures is inserted into the list paths. in paths, the vertex of the parent node being null is the starting vertex. The parent member of each other vertex points to the previous vertex in the shortest path starting from the starting vertex. The member weight of each Pathvertex struct is not used frequently because it is only used when stored in the adjacency table. shows a list of the Pathvertex structures returned when calculating the shortest path in 1.

Example: computing the implementation of the shortest path
/*shortest.c*/#include<float.h>#include<stdlib.h>#include"graph.h"#include"graphalg.h"#include"list.h"#include"set.h"/*relax releasing edges, updating shortest path estimates, updating parent nodes*/Static voidRelax (Pathvertex *u, Pathvertex *v,Doubleweight) {    /*releasing the edges between the vertices u and v*/    if(V->d > U->d +weight) {v= U->d +weight; V->parent =u; }    return;}/*Shortest Shortest path calculation function*/intShortest (Graph *graph,ConstPathvertex *start, List *paths,int(*match) (Const void*key1,Const voidKey2)) {Adjlist*adjlist; Pathvertex*pth_vertex, *Adj_vertex; LISTELMT*element, member; Doubleminimum; intFound,i; /*initialize all vertices in a diagram*/found=0;  for(element = List_head (&graph_adjlists (graph)); element = NULL; element =List_next (Element)) {Pth_vertex= ((Adjlist *) List_data (Element))Vertex; if(Match (Pth_vertex, start)) {/*Locate and initialize the start vertex*/Pth_vertex->color =White ; Pth_vertex->d =0; Pth_vertex->parent =NULL; Found=1; }        Else        {            /*non-starting vertex, initializing*/Pth_vertex->color =White ; Pth_vertex->d =Dbl_max; Pth_vertex->parent =NULL; }    }    /*If the start vertex is not matched, the program exits*/    if(!found)return-1; /*use the Dijkstra algorithm to calculate the shortest path starting from the starting vertex*/I=0;  while(I <Graph_vcount (graph)) {        /*from all white vertices, select the vertex with the shortest path estimate minimum*/Minimum=Dbl_max;  for(Element=list_head (&graph_adjlists graph); element!=null; element =List_next (Element)) {Pth_vertex= ((adjlist*) List_data (Element))Vertex; if(Pth_vertex->color = = White && Pth_vertex->d <minimum) {Minimum= pth_vertex->D; Adjlist=list_data (Element); }        }        /*Paint the vertex black*/((Pathvertex*) Adjlist->vertex)->color =Black; /*traverse vertices adjacent to the selected vertex*/         for(Member=list_head (&adjlist->adjacent); member! = NULL; member =List_next (member)) {Adj_vertex=List_data (member);  for(element = List_head (&graph_adjlists (graph)); element = NULL; element =List_next (Element)) {Pth_vertex= ((Adjlist *) List_data (Element))Vertex; if(Match (Pth_vertex, Adj_vertex)) {Relax (adjlist->vertex, Pth_vertex, adj_vertex->weight); }}} I++; }    /*inserts each black Pathvertexx structure in the list of contiguous table structures into the list paths*/List_init (paths,null);  for(Element=list_head &graph_adjlists (graph)); element!=null; element=List_next (Paths,null)) {        /*load each black vertex in the list of adjacency table Structures*/Pth_vertex= ((Adjlist *) List_data (Element))Vertex; if(Pth_vertex->color = =Black) {            if(List_ins_next (Paths, List_tali (paths), Pth_vertex)! =0) {List_destroy (paths); return-1; }        }    }    return 0;}

Shortest path instance: routing table

a very important application of the shortest path algorithm in the real world is to route data in the Internet . Routing is the decision-making process of transferring data from one point to another. In the Internet, routing is the process of propagating data segments or packets along interconnected points, called gateways. When a packet passes through a gateway, the router looks at the final destination of the packet and then sends the packet to the next gateway. The purpose of a router is to send packets to the location closest to the destination.

In order to send packets to the place closest to the destination, each router maintains the structure or topology information of the Internet. This information is stored in the routing table. The routing table stores an entry for each router that knows how to reach the gateway. Each entry specifies the address that sends the data to the next gateway.

Because routers periodically update their routing tables as the Internet changes, packets are routed as closely as possible along the best path. There is one type of route called the shortest path priority route or SPF route, where each router maintains its own network diagram so that it can update its routing table by calculating the shortest path between itself and other nodes . The Internet topology diagram is a weighted graph with the vertices as gateways and the edges as the connecting lines between the gateways. The weight of the edge is determined by the performance of the connection path . Occasionally, routers Exchange topology and performance information, and a protocol is specifically designed to do this.

Design the function route and use the SPF routing algorithm to calculate the information needed to update the entries in the routing table .

the function accepts a list of path information returned in the paths parameter of shortest .

It uses this information to determine the next gateway the router will send packets to to ensure that the gateway is a step closer to the destination.

To complete a complete table for the specified gateway, first call the function shortest, where the gateway is passed in by the start parameter .

Next, for the destination address contained in each routing table, call the function route, where the destination address is passed in by destination .

This address is then passed into match as provided in Figure graph_init of the path generated from the paths to the match function.

The route function points the parent node pointer in the destination list paths to the gateway and returns the best node for the routed packet (this node is stored in the output parameter next). The vertices returned in next point to the actual vertices in the paths, so it must be valid as long as you can access the memory space in the next,paths.

Part A shows the calculation process of the routing table of a router in the Internet. Part B shows the process of computing the routing table for routers that deal with B. Note that the shortest path is different depending on the starting position in the Internet. It is also important to note that there is no way to reach a in figure B, so there are no related entries in the table.

The time complexity for calculating routes is O (N2), where n is the number of gateways in paths.

Example: function implementation for updating entries in the routing table
/*route.c*/#include<stdlib.h>#include"graphalg.h"#include"list.h"#include"route.h"/*Route*/intRoute (List *paths, Pathvertex *destination, Pathvertex **next,int(*match) (Const void*key1,Const void*Key2)) {Pathvertex*Temp,*parent; LISTELMT*element; intfound; /*find the destination address in the gateway linked list*/found=0;  for(element = List_head (paths); Element! = NULL; element =List_next (Element)) {        if(Match (List_data (element), destination)) {temp=list_data (Element); Parent= ((Pathvertex *) List_data (Element))parent; Found=1;  Break; }    }    /*If no destination address is found, function exits*/    if(!found)return-1; /*calculate the next gateway to the shortest path to the destination*/     while(parent!=NULL) {Temp=list_data (Element); Found=0;  for(element = List_head (paths); Element! = NULL; element =List_next (Element)) {            if(Match (List_data (element), parent)) {Parent= ((Pathvertex *) List_data (Element))parent; Found=1;  Break; }        }        /*if the target cannot be reached, the function exits*/        if(!found)return-1; }    *next =temp; return 0;}

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.