作业要求:给定图数据文件(tinyG.txt),计算得到图的邻接矩阵,并把邻接矩阵保存到文件(tinyG_matrix.txt)中。类名:GraphRepresentation。
用java实现无向图的表示,代码如下:
/**
* 无向图的表示
*/
public class GraphRepresentation{
//vertex,顶点数目
private int v;
//edge,边数目
private int e;
//邻接矩阵
private int [][] matrix ;
/**
* 初始化
* @param v 顶点数目
* @param e 边数目
*/
public GraphRepresentation(int vartex, int edge){
this.v = vartex;
this.e = edge;
this.matrix = new int[v][v];
}
//两个顶点间存在边,设置矩阵值
public void addEdge(int v1, int v2){
matrix[v1][v2] = 1;
matrix[v2][v1] = 1;
}
//获取邻接矩阵
public int[][] getAdjacencyMatrix(){ return matrix; }
}
测试代码:
public static void main(String[] args){
String path = "D:\\graph";
try(Scanner scanner = new Scanner
(GraphRepresentation.class.getClassLoader().getResourceAsStream("tinyG.txt"));
PrintWriter out = new PrintWriter(new File(path, "tinyG_matrix.txt"));){
//第一行的数字是顶点的数目
int v = scanner.nextInt();
//第二行的数字是边的数目
int e = scanner.nextInt();
GraphRepresentation graph = new GraphRepresentation(v, e);
//读取每条边对应的两个顶点,设置邻接矩阵的值
for (int i = 0; i < e; i++) {
int v1 = scanner.nextInt();
int v2 = scanner.nextInt();
graph.addEdge(v1, v2);
}
//计算无向图的邻接矩阵,并将其写到文件中
int[][] matrix = graph.getAdjacencyMatrix();
for(int i=0; i<v; i++){
for(int j=0; j<v; j++){
out.print(matrix[i][j] + "\t");
}
out.println();
}
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
System.err.println("邻接矩阵已成功写到磁盘上...");
}
测试结果:
温馨提示: 今天愚人节,如果程序有bug,那可能是我在和您开玩笑...