《算法给轮》第四周作业——图的表示
来源:互联网 发布:访问nginx图片显示404 编辑:程序博客网 时间:2024/06/18 16:44
编程要求: 图的表示:给定图数据文件(tinyG.txt),计算得到图的邻接矩阵,并把邻接矩阵保存到文件(tinyG_matrix.txt)中。类名:GraphRepresentation。
/** * 程序功能:从文件读出图顶点边数以及点之间的关系,用邻接矩阵 * 表示并且保存至指定文件中 * 作者:冯得晟 * 时间:2014.04.2 */ import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.Scanner;public class ExpressChart {int v;int e;int[][] matrix;static String srcpath="H:\\学习\\大三\\大三 下\\算法概论\\课后作业\\图\\tinyG.txt";static String dispath="H:\\学习\\大三\\大三 下\\算法概论\\课后作业\\图\\tinyG_matrix.txt"; public ExpressChart(){}public ExpressChart(int var,int edg){this.v=var;this.e=edg;this.matrix=new int[v][v];}void readFileByChars(String fileName) {try{Scanner scn=new Scanner(new File(fileName));v=scn.nextInt();//读取文件第一个数字System.out.println("图的节点个数是:"+v);e=scn.nextInt();//读取文件第二个数 System.out.println("图的边的个数是:"+e); ExpressChart ect=new ExpressChart(v,e); for(int i=0;i<e;i++){ int a1=scn.nextInt(); int a2=scn.nextInt(); matrix=ect.getMatrix(a1, a2); }}catch(IOException e){e.printStackTrace();} }void writeFileByChars(String fileName){try{PrintWriter pw=new PrintWriter(new File(fileName));for(int i=0;i<v;i++){for(int j=0;j<v;j++){pw.print(matrix[i][j]+"\t");}pw.println();pw.flush(); //printwriter (file(fileName)) 用这种方式 需要刷新。}System.out.println("矩阵已存入文件。");}catch(IOException e){e.printStackTrace();}}int [][] getMatrix(int v1,int v2){matrix[v1][v2]=1;matrix[v2][v1]=1;return matrix;}public static void main(String[] args){ExpressChart ec=new ExpressChart();ec.readFileByChars(srcpath);ec.writeFileByChars(dispath);}}
运行结果:
存储文件截图
编程总结:虽然这个题目比较简单,在做的过程中也暴露出编程功底弱的特点。譬如数组没有初始化就在使用,造成数组越界的错误。给自己的建议,不管这样的编程题目,都要每个小步骤都完成,譬如构造函数等,从零开始,就稳下来学。
0 0
- 《算法给轮》第四周作业——图的表示
- 第四周作业—图的表示
- 第四周作业—图的表示
- 第四周作业—图的表示
- 第四周作业—图的表示
- 计科《算法设计与分析》第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示(GraphRepresentation)
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 第四周作业——图的表示
- 项目二。3.多文件
- java.nio.ByteBuffer用法小结
- 线索二叉树及相关函数
- Unity3D-NGUI动态加载图片
- ORACLE多会话同时锁表无法解锁解决办法
- 《算法给轮》第四周作业——图的表示
- WM_CTLCOLOR和OnCtlColor消息的用法
- webservice的安全机制2---handler实现
- 深入学习JDK 线程池(之六)
- JSP知识点
- 类加载器---URLClassLoader类
- etc/hosts file
- webservice系列3---chain
- 黑马程序员:C语言基本知识(1)