//拓扑排序
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;
}
}
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+" ");
}
}拓扑排序
精选 转载dongdong200514 博主文章分类:Java/算法
上一篇:LCS最长公共子序列——动态规划
下一篇:并查集1——查找亲戚关系
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
排序算法之计数排序的优化
排序算法之计数排序的优化
数组 计数排序 最小值
















