代码
public class Main {
//用集合存储各个顶点
static ArrayList<String> vertexList;
//用二维数组存储各个边(邻接矩阵)
static int[][] edges;
//保存边的数目
static int numOfEdges = 0;
public static void main(String[] args) {
String[] vertexs = {"A","B","C","D","E"};
createGraph(5);
for (int i = 0;i < vertexs.length;i++){
insertVertex(vertexs[i]);
}
insertEdge(0,1,1);
insertEdge(0,2,1);
insertEdge(1,2,1);
insertEdge(1,3,1);
insertEdge(1,4,1);
show();
}
//初始化图
public static void createGraph(int edgeNums){
vertexList = new ArrayList<String>();
edges = new int[edgeNums][edgeNums];
numOfEdges = edgeNums;
}
//添加顶点
public static void insertVertex(String oneVertex){
vertexList.add(oneVertex);
}
//添加边
public static void insertEdge(int v1,int v2,int weight){
edges[v1][v2] = weight;
edges[v2][v1] = weight;
numOfEdges++;
}
//返回节点的数目
public static int getNumOfVertex(){
return vertexList.size();
}
//返回边的数目
public static int getNumOfEdges(){
return numOfEdges;
}
//返回下标为i的点的数据
public static String getValueByIndex(int index){
return vertexList.get(index);
}
//返回某一边的权值
public static int getWeightByV1V2(int v1,int v2){
return edges[v1][v2];
}
public static void show(){
for (int[] temp: edges){
System.out.println(Arrays.toString(temp));
}
}
}
结果
[0, 1, 1, 0, 0]
[1, 0, 1, 1, 1]
[1, 1, 0, 0, 0]
[0, 1, 0, 0, 0]
[0, 1, 0, 0, 0]