第四周java作业,图的表示
来源:互联网 发布:grub添加linux引导 编辑:程序博客网 时间:2024/05/04 17:04
实现代码如下:
package myhelp.resources;
import java.io.File;import java.io.PrintWriter;
import java.util.Scanner;
public class GraphRepresentation {
private int[] G = new int[2];
private int[][] E;
private int[][] Matrix;
public static void main(String[] args) {
GraphRepresentation t = new GraphRepresentation();
try {
t.read("D:/tinyG.txt");
t.init();
t.writeToFile("D:/tinyG_matrix.txt");
} catch (Exception e) {
e.printStackTrace();
}
}
private void init() {
int n = G[0];
Matrix = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Matrix[i][j] = 0;
}
}
printMatrix();
System.out.println();
for (int m = 0; m < G[1]; m++) {
int index0 = E[m][0];
int index1 = E[m][1];
Matrix[index0][index1] = 1;
Matrix[index1][index0] = 1;
}
printMatrix();
}
private void printMatrix() {
int n = G[0];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
System.out.print(Matrix[i][j] + " ");
}
System.out.println();
}
}
public void read(String fileName) throws Exception {
Scanner scan = new Scanner(new File(fileName));
// 读取顶点与边数
for (int i = 0; i < 2; i++) {
G[i] = scan.nextInt();
}
int h = G[1];
E = new int[h][2];
for (int i = 0; i < h; i++) {
for (int j = 0; j < 2; j++) {
E[i][j] = scan.nextInt();
}
}
scan.close();
}
public boolean writeToFile(String fileName) {
PrintWriter print = null;
int n = G[0];
try {
print = new PrintWriter(fileName);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
print.print(Matrix[i][j] + " ");
}
print.print("\r\n");
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
print.close();
}
return true;
}
}
0 0
- 第四周java作业,图的表示
- 第四周作业 -- 图的表示
- 第四周作业--图的表示
- 第四周作业—图的表示
- 第四周作业---图的表示
- 第四周作业-图的表示
- 第四周作业-图的表示
- 第四周作业---图的表示
- 第四周作业—图的表示
- 第四周作业--图的表示
- 第四周作业—图的表示
- 第四周作业—图的表示
- 第四周作业,图的表示
- 第四周作业:图的表示
- 第四周作业-----图的表示
- 第四周作业-----图的表示
- 第四周作业 图的表示
- 第四周作业 -- 图的表示
- 二分查找
- 从原理出发理解JDK动态代理
- 构建RESTful Web Service - 验证的实现和使用(HTTP 基本认证)
- web开发小技巧:异类的Javascript处理和解析URL的方式
- 个人编程总结细节
- 第四周java作业,图的表示
- 04基于JDBC的认证
- 经典递归问题--放苹果POJ【1664】
- MFC动态创建按钮及添加消息响应
- WikiCourse--关于在线课程的想法
- ThinkPHP框架引导类分析
- 普通管理类程序开发之难度系数、层次之说法
- 黑马程序员 Java面向对象——(匿名)内部类
- suricata的简介以及安装过程