Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
2
Example
• D0 can be represented as a matrix: shortest
path between nodes using 0 intermediates
(direct links)
5
Contd.
• Going through shortest path to vertex 1:
• 1,1: d(1,1)+d(1,1)<d(1,1)? 0+0<0? No
• 1,2: d(1,1)+d(1,2)<d(1,2? 0+3<3? No
• …
• 2,1: d(2,1)+d(1,1)<d(2,1)? ¥+3<¥? No
• 2,2: d(2,1)+d(1,2)<d(2,2)? ¥+3<0? No
• …
• 4,2: d(4,1)+d(1,2)<d(4,2)? 2+3<¥? YES! Update
d(4,2) to 5
• 4,5: d(4,1)+d(1,5)<d(4,5)? 2+-4<¥? YES! Update
d(4,5) to –2 6
Contd.
7
Contd.
• Going through shortest path to vertex 2 (includes
going through vertex 1)
• 1,4: d(1,2)+d(2,4)<d(1,4)? 3+1<¥? YES , update
d(1,4) to 4
• Keep going, when k=5:
8
Contd.
Distance matrix gives the distance of the shortest
path from i to j. By following the node in the path
matrix, we can find the path to get the shortest path
from i to j.
9
• import static javafx.scene.input.KeyCode.M;
•
• /*
• * To change this license header, choose License Headers in Project Properties.
• * To change this template file, choose Tools | Templates
• * and open the template in the editor.
• */
•
• /**
• *
• * @author ahmed
• */
•
• public class algorithm {
• static int[][] P;
• static final int N=4;
• public static void main(String[] args){
• int[][] M={{0,5,999,999},{50,0,15,5},{30,999,0,15},{15,999,5,0}};
• P=new int[N][N];
• System.out.println("Matrix to find the shortest path of.");
• printMatrix(M);
• System.out.println("shortest path matrix.");
• printMatrix(FloydAlgo(M));
• System.out.println("path matrix");
• printMatrix(P);
• }
2019/10/15
• public static int[][] FloydAlgo(int[][] M){
• for(int k=0;k<N;k++){
• for(int i=0;i<N;i++){
• for(int j=0;j<N;j++){
• // to keep track;
• if(M[i][k]+M[k][j]<M[i][j]){
• M[i][j]=M[i][k]+M[k][j];
• P[i][j]=k;
•
• }
• // or not to keep track;
• //M[i][j]=min(M[i][j],M[i][k]+M[k][j]);
•
• }
• }
• }
• return M;
2019/10/15
• }
•
• public static int min(int i,int j){
• if(i>j){
• return j;
• }
• return i;
• }
• public static void printMatrix(int[][] Matrix){
• System.out.print("\n\t");
• for(int j=0;j<N;j++){
• System.out.print(j+"\t");
•
• }
• System.out.println();
• for(int j=0;j<35;j++){
• System.out.print("-");
•
• }
2019/10/15
• System.out.println();
• for(int i=0;i<N;i++){
• System.out.print(i + " |\t");
• for(int j=0;j<N;j++){
• System.out.print(Matrix[i][j]);
• System.out.print("\t");
• }
• System.out.println("\n");
• }
• System.out.println("\n");
• }
• }
2019/10/15