Ten commonly used algorithms (9) – Freudian algorithm
The blog instructions
The information involved in the article comes from the Internet collation and personal summary, meaning is the summary of personal learning and experience, if there is any infringement, please contact me to delete, thank you!
introduce
- Floyd algorithm is also an algorithm used to find the shortest path between vertices in a given weighted graph
Shortest path problem
- There are seven villages in Shengli Township (A, B, C, D, E, F, G).
- The distance of each village is represented by A line (weight), for example, A — B is 5 km away
- Q: How do you calculate the shortest distance from each village to each other?
Train of thought
- If the shortest path from vertex vi to vertex vk is known to be Lik, the shortest path from vertex vk to vj is known to be Lkj, and the path from vertex vi to vj is Lij, then the shortest path from vi to vj is min((Lik+Lkj),Lij), and the value of vk is all the vertices in the figure, then the shortest path from vi to vj can be obtained
- The shortest path from vi to vk, Lik, or the shortest path from vk to vj, Lkj, is obtained in the same way
Code implementation
package com.atguigu.floyd;
import java.util.Arrays;
public class FloydAlgorithm {
public static void main(String[] args) {
char[] vertex = { 'A'.'B'.'C'.'D'.'E'.'F'.'G' };
int[][] matrix = new int[vertex.length][vertex.length];
final int N = 65535;
matrix[0] = new int[] { 0.5.7, N, N, N, 2 };
matrix[1] = new int[] { 5.0, N, 9, N, N, 3 };
matrix[2] = new int[] { 7, N, 0, N, 8, N, N };
matrix[3] = new int[] { N, 9, N, 0, N, 4, N };
matrix[4] = new int[] { N, N, 8, N, 0.5.4 };
matrix[5] = new int[] { N, N, N, 4.5.0.6 };
matrix[6] = new int[] { 2.3, N, N, 4.6.0 };
Graph graph = newGraph(vertex.length, matrix, vertex); graph.floyd(); graph.show(); }}class Graph {
private char[] vertex;
private int[][] dis;
private int[][] pre;
public Graph(int length, int[][] matrix, char[] vertex) {
this.vertex = vertex;
this.dis = matrix;
this.pre = new int[length][length];
for (int i = 0; i < length; i++) { Arrays.fill(pre[i], i); }}public void show(a) {
char[] vertex = { 'A'.'B'.'C'.'D'.'E'.'F'.'G' };
for (int k = 0; k < dis.length; k++) {
for (int i = 0; i < dis.length; i++) {
System.out.print(vertex[pre[k][i]] + "");
}
System.out.println();
for (int i = 0; i < dis.length; i++) {
System.out.print("("+vertex[k]+"(including 1/2 level"+vertex[i]+"(including A x I ¶ IA, delighted many customers and ¶ EC" + dis[k][i] + ")"); } System.out.println(); System.out.println(); }}public void floyd(a) {
int len = 0;
for(int k = 0; k < dis.length; k++) {
for(int i = 0; i < dis.length; i++) {
for(int j = 0; j < dis.length; j++) {
len = dis[i][k] + dis[k][j];
if(len < dis[i][j]) {
dis[i][j] = len;
pre[i][j] = pre[k][j];
}
}
}
}
}
}
Copy the code
Thank you
Yet in silicon valley
And hard-working self, personal blog, GitHub