图的表示方式

二维数组表示(邻接矩阵)、链表表示(邻接表)数组加链表

图的创建和代码实现

存储顶点String 使用 ArrayList

import java.util.ArrayList;
import java.util.Arrays;

public class Graph {
private int[][] edrges;
private ArrayList<String> vertexList;
private int numOfEdges;
public static void main(String[] args) {
//测试是否创建成功
int n = 5;
String VertexValue[]={"A","B","C","D","E"};

Graph graph =new Graph(n);
for (String value: VertexValue
) {
graph.insertVertex(value);
}
//添加边
graph.insertEdge(0, 1, 1);
graph.insertEdge(0, 2, 1);
graph.insertEdge(1, 2, 1);
graph.insertEdge(1, 3, 1);
graph.insertEdge(1, 4, 1);
graph.showGraph();
}
//构造器
public Graph(int n){
edrges =new int[n][n];
vertexList = new ArrayList<String>(n);
numOfEdges =0;
}
//返回节点的个数
public int getNumOfVertex(){
return vertexList.size();
}

//得到边的数目
public int getNumOfEdges(){
return numOfEdges;
}

//显示图对应的矩阵
public void showGraph(){
for (int[] link: edrges
) {
System.out.println(Arrays.toString(link));
}
}

//插入节点
public void insertVertex(String vertex){
vertexList.add(vertex);
}


//添加边
public void insertEdge (int v1,int v2,int weight){
edrges[v1][v2] =weight;
edrges[v2][v1] =weight;
numOfEdges++;
}
}