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一米阳光 阅读(362) 评论(0)  编辑  收藏 所属分类: JAVA源码总结备用

只有注册用户登录后才能发表评论。


网站导航: