第四周作业——图的表示

本文介绍了一种通过邻接矩阵表示图数据的方法,并提供了一个Java实现案例。该方法读取图数据文件,构建邻接矩阵,并将其写入新的文本文件。适用于初学者了解图的基本表示形式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 图的表示:给定图数据文件(tinyG.txt),计算得到图的邻接矩阵,并把邻接矩阵保存到文件(tinyG_matrix.txt)中。类名:GraphRepresentation。摘自《Algorithms, 4th Edition》P522博文标题:第四周作业——图的表示


====


package SYS4;

import java.io.*;
import java.util.*;

public class GraphRepresentation {
	
	//将图数据用数组表示
	public static ArrayList read(String path){
		ArrayList<Integer> list=new ArrayList<Integer>();
		BufferedReader input=null;
		
		try{
			FileReader in=new FileReader(path);
			input=new BufferedReader(in);
			String ss;
			
			try{
				while((ss=input.readLine())!=null){
					String[] s=(ss.split(" "));
					for(int i=0;i<s.length;i++){
						list.add(Integer.parseInt(s[i].trim()));//?动态数组存储
					}
				}
			}catch(IOException e){
				e.printStackTrace();
			}
				
			in.close();
			input.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		return list;
	}		
	
	//将图数据用邻接矩阵数组函数表示
	public static int[][] FormGraph(ArrayList<Integer>list){
		int v=list.get(0);//图的顶点
		int e=list.get(1);//图的边
		
		int arc[][]=new int[v][e];
							
		for(int i=0;i<v;i++){
			for(int j=0;j<v;j++){
				arc[i][j]=0;
			}
		}
		
		//用1表示相邻顶点存在边
		for(int k=0;k<e;k++){
			for(int l=2;l<(list.size()-2);l=l+2){
				arc[list.get(l)][list.get(l+1)]=1;
				arc[list.get(l+1)][list.get(l)]=1;
			}
		}
		
		return arc;
	}
	
	//将生成的邻接矩阵写入文件		字节流
	public static void write(int[][] arc){
		File f=new File("e:/tinyG_matrix.txt");
		FileOutputStream ff=null;
		String a="",b="";
		
		try{
			ff=new FileOutputStream(f,false);
			for(int i=0;i<arc.length;i++){
				for(int j = 0;j<arc[0].length;j++){
					a=a+String.valueOf(arc[i][j]);
				}
				a=a+"\t\n";
			}
			ff.write(a.getBytes());//写入
		}catch(Exception e){
			e.printStackTrace();
		}
		
		finally{//?
			try{
				ff.close();//关闭字节流
			}catch(Exception e){
				e.printStackTrace();
			}
		}
	}
	
	
	//主函数
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		String p="e:/tinyG.txt";
		ArrayList<Integer> list=read(p);
		int[][] arc=FormGraph(list);
		
		for(int i=0;i<arc.length;i++){
			for(int j=0;j<arc[0].length;j++){
				System.out.print(arc[i][j]+" ");
			}
			System.out.println();
		}
		write(arc);
	}
	
}

====


文件写入:tinyG_matrix.txt


====



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值