第四周作业 -- 图的表示

本文介绍了一种将图数据(边-边)转换为邻接矩阵存储方式的方法,并提供了一个Java实现示例。该程序能从源文件中读取顶点数和边数,然后构建一个邻接矩阵,并将其保存到指定文件中。

本程序将已有的图数据(边 - 边),图的边数,顶点个数,转换为邻接矩阵存储的方式。

前往了解邻接矩阵




代码如下:


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

public class GraphRepresentation {

	//将生成的矩阵toGraphic写入文件fileName
	public void writeToTxt(int [][] toGraphic,String fileName) throws FileNotFoundException{
		PrintWriter pw = new PrintWriter(new File(fileName));
		int length = toGraphic.length;
		//输出邻接矩阵到指定的文件名fileName
		for(int n=0;n<length;n++){
			for(int m=0;m<length;m++){
				pw.print(toGraphic[n][m]+" ");
			}
			pw.println();
		}
		System.out.println("文件生成成功!");
		pw.close();
	}
	public static void main(String[] args) throws FileNotFoundException{
		//定义读取文件对象,读取顶点数和边数
		Scanner scan = new Scanner(new File(args[0]));//源文件名
		int vertex = scan.nextInt();
		int edge = scan.nextInt();
		
		//定义二维数组,并初始化为0
		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;	
		
		//查询两个顶点是否有边,若有则设置边数为1
		int vertex1,vertex2;
		while(scan.hasNextInt()){
			vertex1 = scan.nextInt();
			vertex2 = scan.nextInt();
			toGraphic[vertex1][vertex2] = 1;
			toGraphic[vertex2][vertex1] = 1;
		}	
		scan.close();
		
		//写到文件
		GraphRepresentation gp = new GraphRepresentation();
		gp.writeToTxt(toGraphic,args[1]);//生成文件名
		
		//读取文件验证结果
		System.out.println("\n读取生成文件验证结果:");
		Scanner scanResult = new Scanner(new File(args[1]));//源文件名
		int count = 0;
		while(scanResult.hasNextInt()){
			count++;
			if(count % 14 != 0)
				System.out.print(scanResult.nextInt()+" ");
			else
				System.out.println();
		}
		scanResult.close();
	}
}


测试结果:



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值