有向图的邻接表表示
来源:互联网 发布:大阪旅游攻略 知乎 编辑:程序博客网 时间:2024/04/30 08:36
package com.zhangweiwei; public class Vt { int data; Edge adj;
}
package com.zhangweiwei;public class Edge {int dest; Edge link; Edge(int D) { dest=D; link=null; } }
package com.zhangweiwei;import java.io.BufferedReader;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;public class GraphRev {public static void main(String[] args) { String path = "txt/tinyDG.txt"; ArrayList<Integer> list = read(path); //图的顶点数 int vn=list.get(0); //图的边数 int en=list.get(1); int b[][] = new int[list.get(1)][2]; //顶点数组 int v[] = new int[list.size()]; //顶点数组初始化 for(int i=0;i<vn;i++){ v[i]=i; } //图的邻接表 int k=2; //最后一个 //将一位数组的值加入到二维数组中 for(int i=0;i<list.get(1);i++){ for(int j=0;j<2;j++){ b[i][j]=list.get(k); k++; } } GraphRev G=new GraphRev(); G.Graphadj(vn, v, en, b); G.display(); } static int DefalutSize=20; private Vt NodeTable[]; //顶点表 private int NumVertices=0; private int NumEdges=0; public void Graphadj(int vn,int v[],int en,int e[][]){ //形参:顶点数 顶点数组 边数 边节点数组 //创建顶点表 NodeTable=new Vt[vn]; //输入顶点 for(int i=0;i<vn;i++){ InsertVt(v[i]); } //输入边 for(int i=0;i<en;i++) { InsertEdge(e[i][0],e[i][1]); } } //增加结点 public boolean InsertVt(int Vt) { Vt t=new Vt(); t.data=Vt; t.adj=null; NodeTable[NumVertices]=t; NumVertices++; return true; } //增加边 public boolean InsertEdge(int v1,int v2){ if(v1>NumVertices||v1<0) return false; if(v2>NumVertices||v2<0) return false; //生成一个边结点 Edge E=new Edge(v2); Edge p=NodeTable[v1].adj; if(p==null) NodeTable[v1].adj=E; else{ while(p.link!=null) p=p.link; p.link=E; } NumEdges++; return true; } public void display(){ Edge p; for(int i=0;i<NumVertices;i++){ System.out.print(NodeTable[i].data+":"); p=NodeTable[i].adj; while(p!=null) { System.out.print(p.dest+" "); p=p.link; } System.out.println(); } } // 读取文件到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