第四周作业——图的表示
来源:互联网 发布:福建广电网络宽带帐号 编辑:程序博客网 时间: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
- 第四周作业—图的表示
- 第四周作业—图的表示
- 第四周作业—图的表示
- 第四周作业—图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示(GraphRepresentation)
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第三周作业——冒泡排序和归并排序
- 基于redis通信协议的客户端RedisServer
- Android四大组件----Service
- Even though the char
- PHP中去掉HTML标签
- 第四周作业——图的表示
- hdu 1025 Constructing Roads In JGShining's Kingdom (LIS)
- In order to understand C++
- Android漫游记(2)---ELF可执行文件格式
- 黑马程序员——C语言的冒泡排序
- In previous chapters,
- 第五周作业——有向图邻接表表示及反向图构造
- js对象属性
- VS2008让项目中的自定义控件编译后自动添加到工具箱中