图数据文件:
计算得到图的邻接矩阵,并把邻接矩阵保存到文件(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[n][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[n][m]+" ");
}
System.out.println();
}
}
}
结果如图: