输出有向图的环路(山债版)

来源:互联网 发布:数据挖掘入门书籍推荐 编辑:程序博客网 时间:2024/05/22 03:42

public class Node {

 int vex;
 Node next;
 public Node(int i){
  vex = i;
  next = null;
 }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Circle {

 static Node adjList[];
 static int visited[];
 static int path[];
 static int qufen[];
 static int num;
 
 public static void main(String[] args) throws IOException{
  Circle fas = new Circle();
  BufferedReader br= new BufferedReader(
        new InputStreamReader(System.in));
  System.out.println("请输入结点个数:");
  num = Integer.parseInt(br.readLine());
  adjList =new Node[num];
  for(int i=0;i<num;i++)
   adjList[i] = new Node(0);
  visited = new int[num];
  qufen  = new int [num];
  path = new int[num*2];
  for(int i=0;i<num;i++){
   System.out.println("从结点 "+i+" 到:");
   String line = br.readLine();
   //System.out.print(line=="/br");

   String svex[] = line.split(" ");
   try{
   for (int j =0;j<svex.length;j++){
    int ivex = Integer.parseInt(svex[j]);
    if(ivex>=num){
     System.err.println("输入数字错误!");
     System.exit(0);
    }
    Node vex = new Node(ivex);
    Node itr = adjList[i];
    while(itr.next!=null)
     itr = itr.next;
    itr.next = vex;
   }
   }catch(Exception e){
    continue;
   }
  }
  for (int i=0;i<num;i++){
   fas.findCyclePath(i);
  }
 }
 void findCyclePath(int begin){
   findCyclesBeginWith(begin,begin,-1);
}
 void findCyclesBeginWith(int begin,int cur,int len){
  qufen[begin] = 1;//区分环的标志
  visited[cur] = 1;//
  len++;
  path[len] = cur;
  Node p = adjList[cur].next;
  int v;
  while(p!=null){
   v = p.vex;
   if(v == begin){
    for(int k=0;k<=len;k++)
     System.out.print(path[k]+"  ");
    System.out.println(begin);
   }
   if(visited[v]==0 && qufen[v]!=1)//环没有重复
    findCyclesBeginWith(begin,v,len);
   p = p.next;
  }
  visited[cur] = 0;
  len--; 
  }
}

 

原创粉丝点击