图的表示方法有两种,一种是邻接表,另一种是邻接矩阵。
本文章采用的是邻接矩阵的表示方式。
例:给定图数据文件(tinyG.txt),计算得到图的邻接矩阵,并把邻接矩阵保存到文件(tinyG_matrix.txt)中。
代码实现:
public class GraphRepresentation {
public static void main(String []args) throws IOException{
ArrayList list = Read("E:/tinyG.txt");
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("");
}
//将邻接矩阵写入txt文件中
write(arc);
}
//读取文件
public static ArrayList Read(String path){
ArrayList<Integer> list = new ArrayList<Integer>();
try{
BufferedReader reader = new BufferedReader(new FileReader(path));
String s;
try{
while((s = reader.readLine()) != null){
String []str = (s.split(" "));
for(int i = 0;i < str.length;i++){
list.add(Integer.parseInt(str[i].trim()));
}
}
}catch (IOException e){
e.printStackTrace();
}
reader.close();
}catch (IOException e){
e.printStackTrace();
}
return list;
}
public static int[][] MGraph(ArrayList<Integer> list){
int v,e;
v = list.get(0);
e = list.get(1);
int[][] arc = new int[v][v];
//邻接矩阵初始化
for(int i = 0;i < v;i++){
for(int j = 0;j < v;j++){
arc[i][j] = 0;}
}
//生成邻接矩阵
for(int i = 0;i <= v;i++){
for(int j = 2;j <= v+2;j = j+2){
arc[list.get(j)][list.get(j+1)] = 1;
arc[list.get(j+1)][list.get(j)] = 1;
}
}
return arc;
}
//写文件
public static void write(int [][]a) throws IOException{
OutputStreamWriter outputStream = new OutputStreamWriter(new FileOutputStream("E:/tinyG_matrix.txt"));
for(int i = 0;i < a.length;i++){
for(int j = 0;j < a[0].length;j++){
outputStream.write(a[i][j]+" ");
}
outputStream.write("\r\n");
}
outputStream.close();
}
}
运行结果:
文本截图: