waysun一路陽光

          不輕易服輸,不輕言放棄.--心是夢的舞臺,心有多大,舞臺有多大。踏踏實實做事,認認真真做人。

            BlogJava :: 首頁 :: 新隨筆 :: 聯系 ::  :: 管理 ::
            167 隨筆 :: 1 文章 :: 64 評論 :: 0 Trackbacks
          來源:http://blog.chinaunix.net/u1/50399/showart_408098.html
          /*
           * @title:拓撲排序
           * @input: 一個有向無環圖,表述為一個鄰接矩陣graph[n][],其中graph[i][0]為頂點i的入度,其余為其后繼結點
           * @output: 一個拓撲序列list
           */

          import java.util.*;
          public class TopologicalSortTest
          {  
             public static void main(String[] args)
             {
                 int[][] graph={{0,1,2,3,},{2,},{1,1,4,},{2,4,},{3,},{0,3,4,},};
                 int[] list=new int[graph.length];;
                 TopologicalSort topologicalSort=new TopologicalSort();
                 topologicalSort.input(graph);
                 list=topologicalSort.getList();
                 for(int l : list){
                     System.out.print(l+" ");
                 }
             }
          }
          class TopologicalSort
          {
           int[][] graph;
           int[] list;
           
              void input(int[][] graph)
              {
               this.graph=graph;
               list=new int[graph.length];
               calculate();
              }
              
              void calculate()
              {
                  Stack stack=new Stack();
                  for(int i=0; i<graph.length; i++){
                   if(graph[i][0]==0){
                    stack.push(i);
                   }
                  }
                  
                  int i=0;
                  while(stack.empty()!=true){
                   list[i]=(Integer)stack.pop();
                   for(int j=1; j<graph[list[i]].length; j++){
                    int k=graph[list[i]][j];
                    if((--graph[k][0])==0){
                     stack.push(k);
                    }
                   }
                   i++;
                  }
                  
                  if(i<graph.length){
                   System.out.println("存在環,不可排序!");
                   System.exit(0);
                  }
              }
              int[] getList()
              {
               return list;
              }
          }
           
          運行結果:
          5 0 3 2 4 1
          posted on 2009-04-15 22:22 weesun一米陽光 閱讀(428) 評論(0)  編輯  收藏 所屬分類: JAVA源碼總結備用
          主站蜘蛛池模板: 北碚区| 石台县| 庆城县| 富裕县| 巨鹿县| 永城市| 石景山区| 安龙县| 图们市| 普洱| 库车县| 唐山市| 杨浦区| 阜阳市| 炎陵县| 金乡县| 崇州市| 新安县| 孝义市| 龙井市| 桃园县| 江川县| 全南县| 克什克腾旗| 北安市| 江达县| 岳阳市| 娱乐| 应城市| 塔城市| 颍上县| 荃湾区| 文昌市| 平凉市| 建湖县| 漳平市| 崇阳县| 翁源县| 孝昌县| 云梦县| 鲁山县|