第四周作业 -- 图的表示

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

public class Graph
{

	// 将生成的矩阵toGraphic写入文件fileName
	public void writeToFile(int[][] graph, String fileName)
			throws FileNotFoundException
	{
		PrintWriter pw = new PrintWriter(new File(fileName));
		int length = graph.length;
		
		// 输出邻接矩阵到指定的文件名fileName
		for (int n = 0; n < length; n++)
		{
			for (int m = 0; m < length; m++)
			{
				pw.print(graph[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();

		// 写到文件
		Graph gp = new Graph();
		gp.writeToFile(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();
	}
}

图的数据如下:



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值