图的表示:给定图数据文件(
tinyG.txt
),计算得到图的邻接矩阵,并把邻接矩阵保存到文件(tinyG_matrix.txt)中。
类名:GraphRepresentation
。
程序运行结果截图:
下面是源代码展示:
package 算法作业;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class GraphRepresentation {
public static void main(String[] args) {
BufferedReader br;
try {
br = new BufferedReader(new FileReader("D:/tinyG.txt"));
int tempChar;
String str = "";
str = br.readLine();
int V = Integer.parseInt(str);
str = br.readLine();
int E = Integer.parseInt(str);
int[][] g = new int[V][V];
str = "";
int a = 0, b = 0;
while ((tempChar = br.read()) != -1){
str = str + (char) tempChar;
if ((char) tempChar == ' ') {
a = Integer.parseInt(str.trim());
str = "";
}
if ((char) tempChar == '\n')
{
b = Integer.parseInt(str.trim());
g[a][b] = 1;
g[b][a] = 1;
str = "";
}
}
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter("D:/tinyG_ad.txt"));
str="";
System.out.println("图 的 邻 接 矩 阵 为 : ");
for(int i=0; i<V; i++) {
for(int j=0; j<V; j++) {
System.out.print(g[i][j]+" ");
str=str+" "+Integer.toString(g[i][j]);
if(j==12){
System.out.println();
bw.write(str);
bw.newLine();
str="";
}
}
}
bw.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
程序运行结果截图: