您的位置:首页 > 其它

第四周作业:图的表示

2014-04-14 23:55 232 查看
图数据文件:



计算得到图的邻接矩阵,并把邻接矩阵保存到文件(tinyG_matrix.txt)中

源程序:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class GraphRepresentation {

public static void main(String[] args) throws FileNotFoundException{

//从文件(tinyG.txt)中读取数据并保存在二维数组中
Scanner sc= new Scanner(new File("tinyG.txt"));
int vertex = sc.nextInt();
int edge = sc.nextInt();
int[][] toGraphic = new int[vertex][edge];
int length = toGraphic.length;
for(int i=0;i<length;i++)
for(int j=0;j<length;j++)
toGraphic[i][j] = 0;
int vertex1,vertex2;
while(sc.hasNextInt()){
vertex1 = sc.nextInt();
vertex2 = sc.nextInt();
toGraphic[vertex1][vertex2] = 1;
toGraphic[vertex2][vertex1] = 1;
}
sc.close();

//邻接矩阵保存到文件(tinyG_matrix.txt)中
PrintWriter pw = new PrintWriter(new File("tinyG_matrix.txt"));
for(int n=0;n<length;n++){
for(int m=0;m<length;m++){
pw.printf(toGraphic
[m]+" ");

}
pw.println();
}
pw.close();

//输出邻接矩阵
System.out.println("生成的邻接矩阵为:");
for(int n=0;n<length;n++){
for(int m=0;m<length;m++){
System.out.print(toGraphic
[m]+" ");

}
System.out.println();
}

}

}


结果如图:




内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: