sunfruit[請訪問http://www.fruitres.cn]

          --我相信JAVA能走得更遠 QQ:316228067

          [原創]圖論應用--最短路徑

              --sunfruit

          求上圖1點到其他各點的最短路徑,依據圖論知識建立矩陣模型,進一步得到代碼如下

          public class ShortPathA {

            private static int[][]
                a = {
                {0, 50, 10, 100000, 45, 100000}, {100000, 0, 15, 100000, 10, 100000}, {20, 100000, 0, 15, 100000, 100000}, {
                100000, 20, 100000, 0, 35, 100000}, {100000, 100000, 1000000, 30, 0, 100000}, {100000, 100000, 100000, 3, 100000, 0}
            };

            private static boolean[] mark = new boolean[a.length];
            public ShortPathA() {
              int Vo = 0; //源點
              //源點到其他各點的距離
              int[] b = new int[a.length];
              DynArrayInt S = new DynArrayInt();
              for (int i = 0; i < a.length; i++) {
                mark[i] = false;
                //b[i] = a[Vo][i];
              }
              int best = -1;
              mark[0] = true;
              b[0] = 0; //{0為源點}
              while (best != 0) {
                best = 0;
                int best_j = 0;
                for (int i = 0; i < b.length; i++)
                {
                  if (mark[i]) //{對每一個已計算出最短路徑的點}
                  {
                    for (int j = 0; j < b.length; j++) {
                      if ( (!mark[j]) && (a[i][j] > 0)) {
                        if ( (best == 0) || (b[i] + a[i][j] < best)) {
                          best = b[i] + a[i][j];
                          best_j = j;
                        }
                      }
                    }
                  }
                }
                if (best > 0) {
                  b[best_j] = best;
                  mark[best_j] = true;
                }

              }
              System.out.println(java.util.Arrays.toString(b));
            }

            public static void main(String[] args) {
              ShortPathA shortpath = new ShortPathA();
            }

          }

          posted on 2006-10-23 21:17 sunfruit 閱讀(1702) 評論(0)  編輯  收藏 所屬分類: 數據結構


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 焦作市| 行唐县| 大英县| 阜康市| 九寨沟县| 大石桥市| 南江县| 古蔺县| 湾仔区| 西藏| 海门市| 望江县| 孟津县| 资兴市| 襄樊市| 同仁县| 萨嘎县| 迭部县| 东安县| 张家港市| 郎溪县| 大宁县| 察雅县| 常山县| 谢通门县| 花垣县| 扎赉特旗| 遵化市| 长葛市| 海淀区| 遂平县| 山西省| 株洲市| 旬阳县| 崇义县| 靖安县| 双柏县| 桑日县| 天柱县| 弥渡县| 独山县|