資源簡介
解決任意兩點間的最短路徑的一種算法,可以正確處理有向圖或負權的最短路徑問題,同時也被用于計算有向圖的傳遞閉包。Floyd-Warshall算法的時間復雜度為O(N3),空間復雜度為O(N2)。
java代碼實現。算法詳解,參考技術文檔
https://www.jianshu.com/p/db0df9197073
代碼片段和文件信息
package?a;
/**
?*? ┏┓ ┏┓+?+
?*? ┏┛┻━━━┛┻┓?+?+
?*? ┃ ┃
?*? ┃ ━ ┃?++?+?+?+
?*? ?████━████?┃+
?*? ┃ ┃?+
?*? ┃ ┻ ┃
?*? ┃ ┃?+?+
?*? ┗━┓ ┏━┛
?*? ┃ ┃
?*? ┃ ┃?+?+?+?+
?*? ┃ ┃ Code?is?far?away?from?bug?with?the?animal?protecting
?*? ┃ ┃?+? 神獸保佑代碼無bug
?*? ┃ ┃
?*? ┃ ┃ +
?*? ┃ ? ┗━━━┓?+?+
?*? ┃? ┣┓
?*? ┃? ┏┛
?*? ┗┓┓┏━┳┓┏┛?+?+?+?+
?*? ┃┫┫ ┃┫┫
?*? ┗┻┛ ┗┻┛+?+?+?+
?*
?*?@Author:Halburt
?*?@Date:2019-04-23?下午?1:52
?*?@Description:?Floyd算法demo
?*/
public?class?FloydDemo?{
????//????表示無窮大?即不可達
????public?static?int?MAX?=?Integer.MAX_VALUE;
????//????距離矩陣
????public?int[][]?dist;
????//????路徑Path矩陣
????public?int[][]?path;
????/**
?????*?按點初始化
?????*
?????*?@param?size
?????*/
????public?FloydDemo(int?size)?{
????????this.path?=?new?int[size][size];
????????this.dist?=?new?int[size][size];
????}
????public?static?void?print(int[][]?arrs)?{
????????System.out.println(“------------------------“);
????????for?(int[]?arr?:?arrs)?{
????????????for?(int?a?:?arr)?{
????????????????if?(a?==?FloydDemo.MAX)?{
????????????????????System.out.print(“∞?“);
????????????????}?else?{
????????????????????System.out.print(a?+?“?“);
????????????????}
????????????}
????????????System.out.println();
????????}
????????System.out.println(“------------------------“);
????}
????/**核心算法
?????*?構建距離矩陣和路徑矩陣
?????*?@param?matrix
?????*/
????public?void?floyd(int[][]?matrix)?{
//????????matrix和path?length不一致可處理異常
????????int?size?=?matrix.length;
????????//初始化?dist?和?path
????????for(int?i?=?0;i????????
評論
共有 條評論