邻接矩阵创建图用的二维数组创建图,是用顺序存储结构实现的;
邻接矩阵创建图的过程也就是给二维数组赋值的过程
图的数据结构:
public class Graph { String[] vertex = new String[5]; //顶点类型可自定义 int[][] edge = new int[5][5]; //边的类型可自定义 .... //为了简洁,省略get,set方法 }
实现和测试:
public class GraphApp { public static void main(String[] args){ Graph g = createGraphByMatrix(); printGraph(g); } /** * 邻接矩阵创建图 * 顶点集合 {A,B,C,D,E} * 边集合{(A,B),(B,C),(C,D),(D,E),(E,A),(A,C)} ->{(0,1),(1,2),(2,3),(3,4),(4,1),(0,2)} * 顶点数就是二维数组边集的维数 */ public static Graph createGraphByMatrix(){ Graph g = new Graph(); Scanner sc = new Scanner(System.in); //给顶点赋值,此处只是赋予名称 for(int i = 0; i < g.getVertex().length; i++){ System.out.println("输入顶点名称:"); String vertexName = sc.next(); g.getVertex()[i] = vertexName; } //初始化邻接矩阵 for(int i = 0; i < g.getVertex().length; i++){ for(int j = 0; j < g.getVertex().length; j++){ g.getEdge()[i][j] = 0; //两顶点之间没有边 此处我们用 0代替 一般用无穷大代替 } } //输入边数 System.out.println("输入边数:"); int edgeNum = sc.nextInt(); int edgeMaxNum = g.getVertex().length * (g.getVertex().length-1)/2; //无向图最大边数 n*(n-1)/2 if(edgeNum > edgeMaxNum){ System.out.println("边数不能超过无向图的最大边数!"); System.exit(0); } //给邻接矩阵赋值 for(int i = 0; i < edgeNum; i++){ System.out.println("输入边(vi,vj)上的下标i"); int edgI = sc.nextInt(); System.out.println("输入边(vi,vj)上的下标j"); int edgJ = sc.nextInt(); System.out.println("输入边(vi,vj)上的权值:"); int weight = sc.nextInt(); g.getEdge()[edgI][edgJ] = weight; g.getEdge()[edgJ][edgI] = weight; //无向图有对称性 a[i][j] = a[j][i] } return g; } private static void printGraph(Graph g){ for(int i = 0; i < g.getVertex().length; i++){ System.out.print(g.getVertex()[i] + " "); } System.out.println(); for(int i = 0; i < g.getVertex().length; i++){ for(int j = 0; j < g.getVertex().length; j++){ System.out.print(g.getEdge()[i][j] +" "); } System.out.println();; } } }
打印结果:
A B C D E
0 1 6 0 0
1 0 2 0 5
6 2 0 3 0
0 0 3 0 4
0 5 0 4 0