- package graph;
- import java.io.File;
- import java.io.PrintWriter;
- import java.util.Scanner;
- public class Graph{
- private int v;
- private int e;
- private int [][] matrix ;
- public Graph(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){
- try(Scanner scanner = new Scanner(new File("tinyG.txt"));
- PrintWriter out = new PrintWriter(new File("tinyG_matrix.txt"));){
- int v = scanner.nextInt();
- int e = scanner.nextInt();
- Graph graph = new Graph(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] + " ");
- }
- out.println();
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.err.println("邻接矩阵已写到“tinyG_matrix.txt”");
- }
- }