第四周作业——图的表示
2014-04-02 12:29
274 查看
1. 图的表示:给定图数据文件(tinyG.txt),计算得到图的邻接矩阵,并把邻接矩阵保存到文件(tinyG_matrix.txt)中。类名:GraphRepresentation。摘自《http://algs4.cs.princeton.edu/home/》P522。
![](http://img.blog.csdn.net/20140402120947656)
思路:
先把要读取的文件读入并保存到数组中。由于读取进来的是字符类型,所以在保存进数组前要先进行类型转换。然后根据邻接矩阵的性质把该图的邻接矩阵表示出来。
运行结果:
![](http://img.blog.csdn.net/20140402122743703)
实现代码: import java.io.*; public class GraphRepresentation { public static void main(String[] args) { try { FileReader fr=new FileReader("F:\\tinyG.txt"); BufferedReader br=new BufferedReader(fr); int v,e; String str=""; str=br.readLine(); v=Integer.parseInt(str); str=""; str=br.readLine(); v=Integer.parseInt(str); int[][] g=new int[v][v]; int a,b; for(a=0;a<v;a++) for(b=0;b<v;b++) g[a][b]=0; str=""; int t1; while((t1=br.read())!=-1) { str = str + (char) t1; if((char)t1==' ') { a = Integer.parseInt(str.trim()); str=""; } if((char)t1=='\n') { b = Integer.parseInt(str.trim()); g[a][b]=1; g[b][a]=1; str=""; } } br.close(); fr.close(); FileOutputStream fos = new FileOutputStream("f:\\tinyG_matrix.txt"); OutputStreamWriter osw = new OutputStreamWriter(fos, "gb2312"); BufferedWriter bw = new BufferedWriter(osw); str=""; System.out.println("该图的邻接矩阵为: "); for(a=0;a<v;a++) { for(b=0;b<v;b++) { System.out.print(g[a][b]+" "); str=str+Integer.toString(g[a][b]); } System.out.println(); bw.write(str); bw.newLine(); str=""; } bw.close(); osw.close(); } catch (NumberFormatException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
思路:
先把要读取的文件读入并保存到数组中。由于读取进来的是字符类型,所以在保存进数组前要先进行类型转换。然后根据邻接矩阵的性质把该图的邻接矩阵表示出来。
运行结果: