package com.atguigu;
import java.util.ArrayList;
import java.util.Arrays;
public class Grahph {
private ArrayList<String> vertexList; //儲存頂點集合
private int[][] edges; //儲存圖對應的鄰接矩陣
private int numOfEdges; //表示邊的數目
public static void main(String[] args) {
//測試一把圖是否建立ok
int n=5; //結點的個數
String Vertexs[]={"A","B","C","D","E"};
//建立圖物件
Grahph grahph=new Grahph(n);
//迴圈的新增頂點
for(String vertex:Vertexs){
grahph.insertVertex(vertex);
}
//新增邊
grahph.insertEdge(0,1,1);
grahph.insertEdge(0,2,1);
grahph.insertEdge(1,2,1);
grahph.insertEdge(1,3,1);
grahph.insertEdge(1,4,1);
//顯示一把鄰接矩陣
grahph.showGraph();
}
//構造器
public Grahph(int n){
//初始化矩陣和vertexList
edges=new int[n][n];
vertexList=new ArrayList<String>(n);
numOfEdges=0;
}
//圖中常用的方法
//返回結點的個數
public int getNumOfVertex(){
return vertexList.size();
}
//顯示圖對應的矩陣
public void showGraph(){
for(int[] link: edges){
System.out.println(Arrays.toString(link));
}
}
//得到邊的數目
public int getNumOfEdges(){
return numOfEdges;
}
//返回結點i(下標)對應的資料 0->"A" 1->"B" 2->"C"
public String getValueByIndex(int i){
return vertexList.get(i);
}
//插入結點
public void insertVertex(String vertex){
vertexList.add(vertex);
}
//新增邊
public void insertEdge(int v1,int v2,int weight){
//v1表示點的下標即使第幾個頂點 "A"-"B" "A"->0 "B"->1
//v2表示第二個頂點對應的下標
//weight表示
edges[v1][v2]=weight;
edges[v2][v1]=weight;
numOfEdges++;
}
}
輸出
[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]
Process finished with exit code 0