关于图的数据转为为邻接矩阵(第四次作业)

来源:互联网 发布:curl post json body 编辑:程序博客网 时间:2024/05/22 13:49

   代码呈现如下:

package graph;import java.io.BufferedReader;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;public class GraphRepresentation {static int vertexNum;static int arcNum;static int matrix[][];public static void main(String[] args) {try {File file = new File("src/tinyG.txt");InputStreamReader reader = new InputStreamReader(new FileInputStream(file));BufferedReader bufferedreader = new BufferedReader(reader);int index = 1;String str = "";while ((str = bufferedreader.readLine()) != null) {if (index == 1) {    // 读取第一行数字,并作为顶点数附值给vertexNumvertexNum = Integer.parseInt(str.trim());index++;System.out.print("获取图的顶点数为:" + vertexNum + "\n");continue;} else if (index == 2) { // 获取第二行数字,并作为边数赋值给arcNumarcNum = Integer.parseInt(str.trim());index++;System.out.print("获取图的边的个数为:" + arcNum + "\n");continue;} else if (index == 3) { // 获取顶点数和边数构成的二维数组matrix = new int[vertexNum][arcNum];index++;continue;}beconnected(str);}//打印出邻接矩阵并将其保存在预定文件中PrintWriter pw = new PrintWriter(new File("src/tinyG_matrix.txt"));for (int i = 0; i < vertexNum; i++) {for (int j = 0; j < arcNum; j++) {pw.print(matrix[i][j] + "  ");System.out.print(matrix[i][j] + "  ");}pw.flush();pw.println();System.out.println();}System.out.println("所得到的矩阵已经存入预定文件,请去查看!");} catch (NumberFormatException e) {e.printStackTrace();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} //实现将具有相互对应的顶点在矩阵上设为1,其他的默认为0public static void beconnected(String str) {String s[] = str.trim().split(" ");int firstVertex = Integer.parseInt(s[0]);int secondVertex = Integer.parseInt(s[1]);for (int i = 0; i < vertexNum; i++) {matrix[firstVertex][secondVertex] = 1;matrix[firstVertex][secondVertex] = 1;}}}



0 0
原创粉丝点击