您的位置:首页 > 其它

第四周作业——图的表示

2014-04-01 22:27 246 查看
1、图的表示:给定图数据文件(tinyG.txt),计算得到图的邻接矩阵,并把邻接矩阵保存到文件(tinyG_matrix.txt)中。类名:GraphRepresentation

package week_4;

import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;

public class GraphRepresentation {
int v ; //vertex 顶点
int e ; //edge 边的数目
int[][] matrix;   //邻接矩阵

//构造函数,初始化函数
public GraphRepresentation(int v,int e) {
this.v = v;
this.e = e;
matrix = new int[v][e];
}

//两个顶点存在边,设置矩阵的值为1
public void addEdge(int v1,int v2) {
matrix[v1][v2] = 1;
matrix[v2][v1] = 1;
}

//获取邻接矩阵
public int[][] getAdjacentMatrix(){
return matrix;
}

//主函数
public static void main(String[] args){
String path = "d://graph/";
try{
File file = new File(path+"tinyG.txt");
Scanner scan = new Scanner(file);
PrintWriter out = new PrintWriter(path+"tinyG_Matrix.txt");

int v = scan.nextInt();  //读取第一行是顶点的个数
int e = scan.nextInt();  //读取第二行是边的个数

GraphRepresentation graph = new GraphRepresentation(v,e);

//读取每条边对应的顶点,设置邻接矩阵的值
for(int i=0;i<e;i++){
int v1 = scan.nextInt();
int v2 = scan.nextInt();
graph.addEdge(v1, v2);
}

//获取无向图的邻接矩阵,并且写入文件
int[][] matrix = graph.getAdjacentMatrix();
for(int i=0;i<v;i++){
for(int j=0;j<v;j++) {
out.print(matrix[i][j]+"\t");  //显示第一行
}
out.println();  //换行
}
out.close();

}catch(Exception e) {
e.printStackTrace();
//throw new RuntimeException(e.getMessage());

}
System.out.println("邻接矩阵已经成功写入文件…");
}

}


















                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  matrix 邻接矩阵