import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class GraphRepresentation {
int v;
int e;
int[][] matrix;
static String srcpath="F:\\tinyG.txt";
static String dispath="F:\\tinyG_matrix.txt";
public GraphRepresentation(){
}
public GraphRepresentation(int var,int edg){
this.v=var;
this.e=edg;
this.matrix=new int[v][v];
}
void readFileByChars(String fileName) {
try{
Scanner scn=new Scanner(new File(fileName));
v=scn.nextInt();//读取文件第一个数字
e=scn.nextInt();//读取文件第二个数
GraphRepresentation ect=new GraphRepresentation(v,e);
for(int i=0;i<e;i++){
int a1=scn.nextInt();
int a2=scn.nextInt();
matrix=ect.getMatrix(a1, a2);
}
}catch(IOException e){
e.printStackTrace();
}
}
void writeFileByChars(String fileName){
try{
PrintWriter pw=new PrintWriter(new File(fileName));
for(int i=0;i<v;i++){
for(int j=0;j<v;j++){
pw.print(matrix[i][j]+"\t");
}
pw.println();
pw.flush(); //printwriter (file(fileName)) 用这种方式 需要刷新。
}
System.out.println("矩阵已存入文件。");
}catch(IOException e){
e.printStackTrace();
}
}
int [][] getMatrix(int v1,int v2){
matrix[v1][v2]=1;
matrix[v2][v1]=1;
return matrix;
}
public static void main(String[] args){
GraphRepresentation ec=new GraphRepresentation();
ec.readFileByChars(srcpath);
ec.writeFileByChars(dispath);
}
}
运行结果下载:http://download.csdn.net/download/u010917502/7143409