第四周作业——图的表示

来源:互联网 发布:福建广电网络宽带帐号 编辑:程序博客网 时间:2024/06/11 05:58

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 stubString 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

====






0 0