1.
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) {
// TODO 自动生成的方法存根
String path = "D:\\androidtext\\算法作业\\src\\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.txt
write(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.txt
public static void write(int[][] arc) {
File f = new File("D:\\androidtext\\算法作业\\src\\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) {
// TODO: handle exception
e.printStackTrace();
} finally {
try {
fou.close();
} catch (Exception e) {
// TODO Auto-generated catch block
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;
}
}