第五周的作业

来源:互联网 发布:windows运行苹果软件 编辑:程序博客网 时间:2024/04/29 03:06
  1. package algorithm;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.File;  
  5. import java.io.FileReader;  
  6. import java.util.StringTokenizer;  
  7.   
  8. public class GraphReverse {  
  9.     private static int vNum;    //点的个数  
  10.     private static int eNum;    //边的个数  
  11.       
  12.     private static int[][] getData() {  
  13.         int[][] matrix = null;  
  14.           
  15.         try {  
  16.             BufferedReader reader = new BufferedReader (new FileReader(new File("src/dataFile/tinyDG.txt")));  
  17.             vNum = Integer.valueOf(reader.readLine().trim());  
  18.             eNum = Integer.valueOf(reader.readLine().trim());  
  19.             matrix = new int[eNum][2];  
  20.               
  21.             String temp = "";  
  22.             int count = 0;  
  23.             while((temp = reader.readLine()) != null) {  
  24.                 int index = 0;  
  25.                 StringTokenizer str = new StringTokenizer(temp);  
  26.                   
  27.                 while (str.hasMoreElements()) {  
  28.                     matrix[count][index] = Integer.valueOf(str.nextToken());  
  29.                     index++;  
  30.                 }  
  31.                   
  32.                 count++;  
  33.             }  
  34.         } catch (Exception e) {  
  35.             e.printStackTrace();  
  36.         }  
  37.           
  38.         return matrix;  
  39.     }  
  40.   
  41.     /** 
  42.      * function: 
  43.      * 0:有序表的邻接表 
  44.      * 1:反向图的邻接表 
  45.      */  
  46.     private static void getSortedList(int[][] data, int function) {  
  47.         String str = "";  
  48.         int begin=0, end=0;  
  49.           
  50.         if (function == 0) {  
  51.             str = "有序表的邻接表:";  
  52.             begin = 0;  
  53.             end = 1;  
  54.         } else if (function == 1) {  
  55.             str = "反向图的邻接表:";  
  56.             begin = 1;  
  57.             end = 0;  
  58.         }  
  59.           
  60.         System.out.println(str);  
  61.           
  62.         for (int i=0; i<vNum; i++) {  
  63.             System.out.print(i + ": ");  
  64.             for (int j=0; j<data.length; j++) {  
  65.                 if (data[j][begin] == i) {  
  66.                     System.out.print("\t" + data[j][end]);  
  67.                 }  
  68.             }  
  69.             System.out.println("");  
  70.         }  
  71.     }  
  72.       
  73.     public static void main(String[] args) {  
  74.         getSortedList(getData(), 0);  
  75.         getSortedList(getData(), 1);  
  76.     }  
  77. }  



0 0