Shortest Path algorithm

Source: Internet
Author: User

Shortest path-dijkstra algorithm and Floyd algorithm 1, Dijkstra algorithm

1.1, the definition overview
Dijkstra (Dijkstra) algorithm is a typical single-source shortest path algorithm that calculates the shortest path of a node to all other nodes. The main feature is to extend from the center of the starting point to the outer layer until it expands to the end point. Dijkstra algorithm is a very representative shortest path algorithm, in many professional courses as the basic content of the detailed introduction, such as data structure, graph theory, operations research and so on. Note that the algorithm requires no negative weight edges in the graph.

Problem Description: In the g= graph (v,e), assume that each edge e[i] length is w[i], find the shortest path from vertex V0 to the remaining points. (Single source shortest path)

1.2, algorithm description
1) algorithm idea: Set g= (V,e) is a weighted graph, the figure of the vertex set V is divided into two groups, the first set of the shortest path has been found in the vertex set (s), the initial s only one source point, after each to find a shortest path , it will be added to the set S, until all vertices are added to s, the algorithm ends, and the second set is the set of vertices of the remaining indeterminate paths (denoted by u), and the second set of vertices is added to s in ascending order of shortest path length. During the join process, the shortest path length that is always maintained from the source Point V to the vertices in S is not longer than the shortest path length from the source point V to any vertex in U. In addition, each vertex corresponds to a distance, the distance from the vertex in S is the shortest path length from V to the vertex, and the distance from the vertex in U is the current shortest path length from V to the vertex that includes only the vertex in S as the middle vertex.

2) algorithm steps:
A. Initially, S contains only the source point, that is, the distance of S={v},v is 0. U contains other vertices other than V, that is: u={remaining vertices}, if V and u in vertex u have edges, then <u,v> normal right value, if U is not V's out edge adjacency point, then <u,v> weight is ∞.
B. Select a minimum distance v from U, K, and add K to S (the selected distance is the shortest path length of V to K).
C. Change the distance between vertices in the U with K as the new consideration, and if the distance from the source point v to the vertex u (through vertex K) is shorter than the original distance (without the vertex K), modify the distance value of the vertex u, the distance of the vertex k of the modified distance value, and the right on the edge.
D. Repeat steps b and c until all vertices are contained in S. The

performs an animation process such as

The code is implemented as follows:

public class Graphbymatrix {
public static Final Boolean undirected_graph = false;//No Direction graph flag
public static Final Boolean directed_graph = true;//Graph flag

public static Final Boolean Adjacency_matrix = true;//adjacency Matrix implementation
public static Final Boolean adjacency_list = false;//adjacency Table implementation

public static final int max_value = Integer.max_value;
Private Boolean Graphtype;
Private Boolean method;
private int vertexsize;
private int Matrixmaxvertex;

One-dimensional array that stores all vertex information
Private object[] Vertexesarray;
A two-dimensional array of relationships between vertices in a stored graph, and the relationship of edges
Private int[][] Edgesmatrix;

Record if I have been accessed by the first node
Private boolean[] visited;

/**
* @param the type of Graphtype chart: graph with direction/no map
* @param method Chart implementation: adjacency Matrix/adjacency Table
*/
Public Graphbymatrix (Boolean Graphtype, Boolean method, int size) {
This.graphtype = Graphtype;
This.method = method;
this.vertexsize = 0;
This.matrixmaxvertex = size;

if (This.method) {
visited = new Boolean[matrixmaxvertex];
Vertexesarray = new Object[matrixmaxvertex];
Edgesmatrix = new Int[matrixmaxvertex][matrixmaxvertex];

Initialize an array with no edges associated with the maximum value of type integer
for (int row = 0; row < edgesmatrix.length; row++) {
for (int column = 0; column < edgesmatrix.length; column++) {
Edgesmatrix[row][column] = Max_value;
}
}

}
}

/******************** Shortest Path ****************************/
Calculates the shortest distance from one vertex to another
public void Dijkstra (Object obj) throws Exception {
Dijkstra (Getvertexindex (obj));
}
public void Dijkstra (int v0) {
int[] dist = new Int[matrixmaxvertex];
int[] prev = new Int[matrixmaxvertex];

Initialize visited, dist, and path
for (int i = 0; i < vertexsize; i++) {
The shortest path is assumed at first
Dist[i] = Edgesmatrix[v0][i];
Visited[i] = false;

The final pass in the direct case is the starting point.
if (i! = V0 && Dist[i] < Max_value)
Prev[i] = V0;
Else
Prev[i] =-1; No direct path
}

Initial source point v0∈visited set, which indicates that the shortest path to V0 to V0 has been found
Visited[v0] = true;

It is assumed that by passing one point to the remaining points, it will be nearer to verify
It is assumed that the two-point relay will be closer, verifying the,.....
Until all possible transit points are exhausted.
int mindist;
int v = 0;
for (int i = 1; i < vertexsize; i++) {
Pick a distance nearest via dot, subscript load V
Mindist = Max_value;

for (int j = 0; J < Vertexsize; J + +) {
if ((!visited[j]) && Dist[j] < mindist) {
v = j; Shorter distances through the vertex J Relay
Mindist = Dist[j];
}
}
VISITED[V] = true;

/* Vertex v is incorporated into S, and the shortest path from V0 to v Vertex is min.
It is assumed that from V0 to V, and then from V to the remaining points, update the current last pass point and distance */
for (int j = 0; J < Vertexsize; J + +) {
if ((!visited[j]) && Edgesmatrix[v][j] < Max_value) {

if (Mindist + edgesmatrix[v][j] <= Dist[j]) {
If the shortest path to the J Point via a V-point is shorter, the update
DIST[J] = mindist + edgesmatrix[v][j];

PREV[J] = v; Number of points via point
}

}
}

}

for (int i = 1; i < Matrixmaxvertex; i++) {
SYSTEM.OUT.PRINTLN ("* *" + vertexesarray[v0] + "-" +vertexesarray[i] + "The Shortest path is:" + dist[i]);
}
}

Gets the corresponding index of the vertex value in the array
private int Getvertexindex (Object obj) throws Exception {
int index =-1;
for (int i = 0; i < vertexsize; i++) {
if (vertexesarray[i].equals (obj)) {
index = i;
Break
}
}
if (index = =-1) {
throw new Exception ("No This value!") ");
}

return index;
}

/**
* Single source shortest path algorithm, used to compute one node to the other!! All nodes!! The shortest Path
*/
public void Dijkstra2 (int v0) {
LinkedList implements the queue interface FIFO
queue<integer> queue = new linkedlist<integer> ();
for (int i = 0; i < vertexsize; i++) {
Visited[i] = false;
}

This loop is to ensure that each vertex is traversed to
for (int i = 0; i < vertexsize; i++) {
if (!visited[i]) {
Queue.add (i);
Visited[i] = true;

while (!queue.isempty ()) {
int row = Queue.remove ();
System.out.print (Vertexesarray[row] + "--");

for (int k = getmin (Row), K >= 0; k = getmin (row)) {
if (!visited[k]) {
Queue.add (k);
Visited[k] = true;
}
}

}
}
}
}

private int getmin (int row) {
int mindist = Max_value;
int index = 0;
for (int j = 0; J < Vertexsize; J + +) {
if ((!visited[j]) && Edgesmatrix[row][j] < mindist) {
Mindist = Edgesmatrix[row][j];
index = j;
}
}
if (index = = 0) {
return-1;
}
return index;
}

public boolean Addvertex (Object val) {
ASSERT (val! = null);
Vertexesarray[vertexsize] = val;
vertexsize++;
return true;
}

public boolean Addedge (int vnum1, int vnum2, int weight) {
ASSERT (vnum1 >= 0 && vnum2 >= 0 && vnum1! = vnum2 && weight >= 0);

A map of the direction
if (Graphtype) {
EDGESMATRIX[VNUM1][VNUM2] = weight;

} else {
EDGESMATRIX[VNUM1][VNUM2] = weight;
EDGESMATRIX[VNUM2][VNUM1] = weight;
}

return true;
}

}

Test:

public void Testweight () throws Exception {
Graphbymatrix graph = new Graphbymatrix (Graph.undirected_graph, Graph.adjacency_matrix, 6);

Graph.addvertex ("1");
Graph.addvertex ("2");
Graph.addvertex ("3");
Graph.addvertex ("4");
Graph.addvertex ("5");
Graph.addvertex ("6");

Graph.addedge (0, 1,7);
Graph.addedge (0, 2,9);
Graph.addedge (0, 5,14);

Graph.addedge (1, 3,15);
Graph.addedge (1, 2,10);

Graph.addedge (2, 3,11);
Graph.addedge (2, 5,2);

Graph.addedge (3, 4,6);
Graph.addedge (4, 5,9);

Graph. Dijkstra (0);
System.out.println ();
Graph. Dijkstra ("1");
System.out.println ();
Graph. DIJKSTRA2 (0);
System.out.println ();
The shortest path to **1-->2 is: 7
The shortest path to **1-->3 is: 9
The shortest path to **1-->4 is: 20
The shortest path to **1-->5 is: 20
The shortest path to **1-->6 is: 11

The shortest path to **1-->2 is: 7
The shortest path to **1-->3 is: 9
The shortest path to **1-->4 is: 20
The shortest path to **1-->5 is: 20

The shortest path to **1-->6 is: 11

1-->2-->3-->6-->4-->5-->

2. Floyd algorithm: Read Freud

1. Definition Overview
The Floyd-warshall algorithm (Floyd-warshall algorithm), also known as the interpolation method, is an algorithm to solve the shortest path between any two points, which can correctly handle the shortest path problem with the direction graph or the negative weight, and is also used to calculate the transitive closure of the graph. The time complexity of the floyd-warshall algorithm is O (N3), and the space complexity is O (N2).

2. Algorithm Description:

1) algorithm thought principle:
The Floyd algorithm is a classical dynamic programming algorithm. In plain language, the first goal is to find the shortest path from point I to J. From the point of view of dynamic planning, we need to make a reinterpretation of this goal (this interpretation is the essence of dynamic planning the most creative)

The shortest path from any node I to any node J is 2 possible, and 1 is straight from I to j,2 from I through several nodes K to J. Therefore, we assume that dis (i,j) is the distance from the shortest path of node u to node V, for each node K, we check whether dis (i,k) + dis (k,j) < dis (I,J) is established, if it is established, prove that the path from I to K to J is shorter than I direct to J Path, We set up dis (i,j) = Dis (i,k) + dis (k,j) so that when we traverse through all nodes K,dis (i,j) The distance from the shortest path of I to J is recorded.

2). Algorithm Description:
A. Start with any one-sided path. The distance between all two points is the right of the edge, and if no edge is connected between the two points, then the right is infinity.
B. For each pair of vertices u and V, see if there is a vertex w so that the path from u to W to V is shorter than known. If it is updated.

3). Calculation----Cross-crossing method for process matrix of Floyd algorithm
Method: Two lines, starting from the upper left corner to the bottom right corner as shown below

Gives the matrix, where matrix A is the adjacency matrix, and the matrix Path records the point at which the shortest path between the U,v two points must pass

The corresponding calculation method is as follows:

The final A3 is the result of the request.

The code is as follows:

public void Shortestpath_floyd () {
int n = vertexsize;
int[][] D = new int[n][n];//Save the minimum path value from I to J
Int[][] p = new int[n][n];//Save the Passing intermediate node
for (int i = 0; i < n; i++) {//Initialize D,p
for (int j = 0; J < N; j + +) {
if (Edgesmatrix[i][j] < Integer.max_value) {

P[I][J] = j;
} else {
P[I][J] =-1;
}
D[I][J] = Edgesmatrix[i][j];
}
}

for (int x = 0; x < n; + +) {//Floyd algorithm, from 0 to n-1 all possible traversal
for (int i = 0; i < n; i++) {
for (int j = 0; J < N; j + +) {
if (D[i][j] > D[i][x] + d[x][j]) {
D[I][J] = D[i][x] + d[x][j];
P[I][J] = p[i][x];
}
}
}
}
Here's a demonstration of the results obtained
for (int i = 0; i < n; i++) {
for (int j = 0; J < N; j + +) {
System.out.print ("" + d[i][j]);
}
System.out.println ();
}
System.out.println ("++++++++++++++++++++++++++++++++++++");
for (int i = 0; i < n; i++) {
for (int j = 0; J < N; j + +) {
System.out.print ("" + p[i][j]);
}
System.out.println ();
}
System.out.println ("+++++++++++++++++++++++++++++++++++");
for (int i = 0; i < n; i++) {
for (int j = 0; J < N; j + +) {
System.out.println ("Output i=" + i + "to j=" + j + "Shortest Path:");
int k = P[i][j];
if (k = =-1) {
System.out.println ("No Shortest Path");
} else {
System.out.print ("" + K);
while (k! = j) {
k = P[k][j];
System.out.print ("" + K);
}
System.out.println ("+k");
System.out.println ();
}
}
}
}

Shortest Path algorithm

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.