实现代码如下:
package myhelp.resources;
import java.io.File;import java.io.PrintWriter;
import java.util.Scanner;
public class GraphRepresentation {
private int[] G = new int[2];
private int[][] E;
private int[][] Matrix;
public static void main(String[] args) {
GraphRepresentation t = new GraphRepresentation();
try {
t.read("D:/tinyG.txt");
t.init();
t.writeToFile("D:/tinyG_matrix.txt");
} catch (Exception e) {
e.printStackTrace();
}
}
private void init() {
int n = G[0];
Matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Matrix[i][j] = 0;
}
}
printMatrix();
System.out.println();
for (int m = 0; m < G[1]; m++) {
int index0 = E[m][0];
int index1 = E[m][1];
Matrix[index0][index1] = 1;
Matrix[index1][index0] = 1;
}
printMatrix();
}
private void printMatrix() {
int n = G[0];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(Matrix[i][j] + " ");
}
System.out.println();
}
}
public void read(String fileName) throws Exception {
Scanner scan = new Scanner(new File(fileName));
// 读取顶点与边数
for (int i = 0; i < 2; i++) {
G[i] = scan.nextInt();
}
int h = G[1];
E = new int[h][2];
for (int i = 0; i < h; i++) {
for (int j = 0; j < 2; j++) {
E[i][j] = scan.nextInt();
}
}
scan.close();
}
public boolean writeToFile(String fileName) {
PrintWriter print = null;
int n = G[0];
try {
print = new PrintWriter(fileName);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
print.print(Matrix[i][j] + " ");
}
print.print("\r\n");
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
print.close();
}
return true;
}
}