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 閱讀(1697) 評論(0)  編輯  收藏 所屬分類: 數據結構


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


          網站導航:
           
          主站蜘蛛池模板: 鹤山市| 嫩江县| 沂源县| 河津市| 南溪县| 葵青区| 伊吾县| 丰台区| 芦山县| 恩施市| 唐河县| 盘锦市| 固原市| 钟祥市| 临城县| 武定县| 邵武市| 泸定县| 宝应县| 泾川县| 通化市| 蒲江县| 馆陶县| 汕头市| 宜良县| 额尔古纳市| 甘泉县| 高邑县| 富裕县| 丰镇市| 会同县| 沁阳市| 高青县| 无棣县| 宁都县| 诸城市| 灯塔市| 通道| 梧州市| 德昌县| 牡丹江市|