第四周:图的表示
来源:互联网 发布:阿里云 ota 安卓 编辑:程序博客网 时间:2024/05/17 07:12
给定图数据文件(tinyG.txt),计算得到图的邻接矩阵,并把邻接矩阵保存到文件(tinyG_matrix.txt)中。类名:GraphRepresentation
package sort;import java.io.BufferedReader;import java.io.File;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;public class GraphRepresentation {public static void main(String[] args) {String path = "D:/tinyG.txt";ArrayList<Integer> list = read(path);// 调用产生邻接矩阵的函数int[][] arc = MGraph(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("");}//写入tinyG_matrix.txtwrite(arc);}// 构造图的邻接矩阵函数public static int[][] MGraph(ArrayList<Integer> list) {// list数组中的前两个数据分别是图的顶点数目和边的数目int v = list.get(0);int e = list.get(1);// 创建一个二维数组arc来存储邻接矩阵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 q = 2; q < list.size() - 2; q = q + 2) {arc[list.get(q)][list.get(q + 1)] = 1;arc[list.get(q + 1)][list.get(q)] = 1;}}return arc;}// 写入tinyG_matrix.txtpublic static void write(int[][] arc) {File f = new File("D:/tinyG_matrix.txt");FileOutputStream fou = null;String a="",b="";try {fou = new FileOutputStream(f, false);// true,设置可追加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";}fou.write(a.getBytes());} catch (Exception e) {e.printStackTrace();} finally {try {fou.close();} catch (Exception e) {e.printStackTrace();}}}// 读取文件到Arraylist 数组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())); // 将String// s中的内容添加到动态数组中}}} catch (IOException e) {// TODO 自动生成的 catch 块e.printStackTrace();}in.close();input.close();} catch (Exception e) {// TODO 自动生成的 catch 块e.printStackTrace();}return list;}}
实验结果如下:
0 0
- 第四周 图的表示
- 第四周:图的表示
- 第四周——图的表示
- 第四周作业 -- 图的表示
- 第四周作业--图的表示
- 第四周作业—图的表示
- 第四周作业---图的表示
- 第四周作业-图的表示
- 第四周作业-图的表示
- 第四周作业---图的表示
- 第四周作业—图的表示
- 第四周作业--图的表示
- 第四周作业—图的表示
- 第四周java作业,图的表示
- 1114第四周 图的表示
- 第四周__图的表示
- 第四周作业—图的表示
- 第四周作业,图的表示
- Facebook揭秘HipHop项目 PHP程序大提速
- JQuery之初探
- ZOJ-1842
- ARM处理器学习之--GPIO操作篇
- C++Primer 顺序容器
- 第四周:图的表示
- ARM 汇编语言源代码行的语法规则
- 第四周作业——图的表示
- 鸟哥linux私房菜学习笔记(6)
- IE6 jquery dialog select无法遮盖
- CallWindowProc与DefWindowProc的区别
- python自然语言处理-学习笔记(一)
- 北京 救生员证书 考试流程
- IDE