拓扑排序-List graph[]实现

import java.util.*;
public class Tuopupaixu2 {
    public static void main(String args[]){
      Scanner in=new Scanner(System.in);
      while(in.hasNext()){
          int n=in.nextInt();
          List<Integer> graph[]=new ArrayList [n+1]; //使用List graph[]形式存储邻接表
          for(int i=0;i<=n;i++)
              graph[i]=new ArrayList<Integer>();
          int du[]=new int[n+1];
          int m=in.nextInt();
          int x,y;
          for(int i=0;i<m;i++){
              x=in.nextInt();
              y=in.nextInt();
              int flag=1;
              for(int j=0;j<graph[x].size();j++){
                  if((int)graph[x].get(j)==y){
                      flag=0;
                      break;
                  }
              }
              if(flag==1){
                  du[y]++;
                  graph[x].add(y);
              }
          }
          int cnt=0;
          Queue<Integer> queue=new LinkedList<Integer>(); //用于拓扑排序
          Queue<Integer> ans=new LinkedList<Integer>();//记录结果
          for(int i=1;i<=n;i++){
              if(du[i]==0){
                  queue.offer(i);
                  ans.add(i);
                  du[i]=-1;
                  cnt++;
              }
          }
          //挨个遍历
          while(queue.size()>0){
              int temp2=queue.poll();
              for(int i=0;i<graph[temp2].size();i++){
                  int temp4=(int)graph[temp2].get(i);
                  du[temp4]--;
                  if(du[temp4]==0){
                      queue.offer(temp4);
                      du[temp4]=-1;
                      ans.add(temp4);
                      cnt++;
                  }
              }
          }
          //判断结果
          if(cnt==n){
              int flag1=1;
              while(ans.size()>0){
                  if(flag1==1){
                      System.out.print(ans.poll());
                      flag1=0;
                  }else{
                      System.out.print(" "+ans.poll());
                  }
              }
              System.out.println();
          }else{
              System.out.println("无法排序");
          }
      }
    }
}

猜你喜欢

转载自blog.csdn.net/anhuibozhoushatu/article/details/83758394