第四周:圖的表示

給定圖數據文件(tinyG.txt),計算得到圖的鄰接矩陣,並把鄰接矩陣保存到文件(tinyG_matrix.txt)中。類名:GraphRepresentation

 

package sort;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class GraphRepresentation {
	public static void main(String[] args) {
	
		String path = "D:/tinyG.txt";
		ArrayList<Integer> list = read(path);
		// 調用產生鄰接矩陣的函數
		int[][] arc = MGraph(list);
		// 控制檯打印鄰接矩陣
		for (int i = 0; i < arc.length; i++) {
			for (int j = 0; j < arc[0].length; j++) {
				System.out.print(arc[i][j]);
			}
			System.out.println("");
		}
		//寫入tinyG_matrix.txt
		write(arc);
	}

	// 構造圖的鄰接矩陣函數
	public static int[][] MGraph(ArrayList<Integer> list) {

		// list數組中的前兩個數據分別是圖的頂點數目和邊的數目
		int v = list.get(0);
		int e = list.get(1);
		// 創建一個二維數組arc來存儲鄰接矩陣
		int arc[][] = new int[v][e];
		// 初始化鄰接矩陣
		for (int i = 0; i < v; i++) {
			for (int j = 0; j < v; j++) {
				arc[i][j] = 0;
			}
		}
		//給鄰接矩陣賦值,1表示邊存在關係
		for (int k = 0; k < e; k++) {
			for (int q = 2; q < list.size() - 2; q = q + 2) {
				arc[list.get(q)][list.get(q + 1)] = 1;
				arc[list.get(q + 1)][list.get(q)] = 1;
			}
		}
		return arc;

	}

	// 寫入tinyG_matrix.txt
	public static void write(int[][] arc) {
		File f = new File("D:/tinyG_matrix.txt");
		FileOutputStream fou = null;
		String a="",b="";
		try {

			fou = new FileOutputStream(f, false);// true,設置可追加
			for (int i = 0; i < arc.length; i++) {
				for (int j = 0; j < arc[0].length; j++) {
					a =a+String.valueOf(arc[i][j]);
				}
				a=a+"\t\n";
			}
			fou.write(a.getBytes());
			
		} catch (Exception e) {
			
			e.printStackTrace();
		} finally {
			try {
				fou.close();
			} catch (Exception e) {
				
				e.printStackTrace();
			}
		}
	}

	// 讀取文件到Arraylist 數組
	public static ArrayList read(String path) {
		ArrayList<Integer> list = new ArrayList<Integer>();
		BufferedReader input = null;
		try {
			FileReader in = new FileReader(path);
			input = new BufferedReader(in);
			String ss;
			try {
				while ((ss = input.readLine()) != null) {
					String[] s = (ss.split(" "));
					for (int i = 0; i < s.length; i++) {
						list.add(Integer.parseInt(s[i].trim())); // 將String
																	// s中的內容添加到動態數組中
					}

				}
			} catch (IOException e) {
				// TODO 自動生成的 catch 塊
				e.printStackTrace();
			}
			in.close();
			input.close();
		} catch (Exception e) {
			// TODO 自動生成的 catch 塊
			e.printStackTrace();
		}

		return list;
	}

}


實驗結果如下:

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章