第四周作业:图的表示
2014-04-14 23:55
232 查看
图数据文件:
![](http://img.blog.csdn.net/20140414234915531?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMDk2NjY1Ng==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
计算得到图的邻接矩阵,并把邻接矩阵保存到文件(tinyG_matrix.txt)中
源程序:
结果如图:
![](http://img.blog.csdn.net/20140414235452765?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMDk2NjY1Ng==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
计算得到图的邻接矩阵,并把邻接矩阵保存到文件(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(); } } }
结果如图: