图的表示

图数据文件:

计算得到图的邻接矩阵,并把邻接矩阵保存到文件(tinyG_matrix.txt)中

 

源程序:

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

public class GraphRepresentation {

	public static void main(String[] args) throws FileNotFoundException{
		
		//从文件(tinyG.txt)中读取数据并保存在二维数组中
		Scanner sc= new Scanner(new File("tinyG.txt"));
		int vertex = sc.nextInt();
		int edge = sc.nextInt();
		int[][] toGraphic = new int[vertex][edge];
		int length = toGraphic.length;
		for(int i=0;i<length;i++)
			for(int j=0;j<length;j++)
				toGraphic[i][j] = 0;	
		int vertex1,vertex2;
		while(sc.hasNextInt()){
			vertex1 = sc.nextInt();
			vertex2 = sc.nextInt();
			toGraphic[vertex1][vertex2] = 1;
			toGraphic[vertex2][vertex1] = 1;
		}	
		sc.close();
		
		
		//邻接矩阵保存到文件(tinyG_matrix.txt)中
		PrintWriter pw = new PrintWriter(new File("tinyG_matrix.txt"));
		for(int n=0;n<length;n++){
			for(int m=0;m<length;m++){
				pw.printf(toGraphic[n][m]+" ");
				
			}
			pw.println();
		}
		pw.close();
		
		
		//输出邻接矩阵
		System.out.println("生成的邻接矩阵为:");
		for(int n=0;n<length;n++){
			for(int m=0;m<length;m++){
				System.out.print(toGraphic[n][m]+" ");
				
			}
			System.out.println();
		}
			
	}

}

 

结果如图:

 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值