邻接矩阵(Adjacency Matrix)
用两个数组来表示图。一个一维数组存储顶点,一个二维数组存储边或者弧。
Java实现
package Graph;
import java.util.ArrayList;
import java.util.List;
public class AdjacencyMatrix<T> {
private List vertex;
private int[][] edges;
private int curEdges; //当前的边数
AdjacencyMatrix(int n){
vertex = new ArrayList(n);
edges = new int[n][n];
curEdges = 0;
}
//顶点、边以、顶点的值以及权值的get方法
public int getCurVertexes() {
return vertex.size();
}
public int getCurEdges() {
return curEdges;
}
public Object getVertexValue(int index){
return vertex.get(index);
}
public int getWeight(int vi, int vj){
return edges[vi][vj];
}
// 插入顶点
public void insertVertex(Object v){
vertex.add(vertex.size(), v);
}
//插入边
public void insertEdge(int vi, int vj, int weight){
edges[vi][vj] = weight;
curEdges ++;
}
//删除顶点
public void deleteVertex(int vi, int vj){
edges[vi][vj] = 0;
curEdges --;
}
//获取顶点的第一个相邻接点
public int getFirstNeighbor(int index){
for(int i = 0; i < vertex.size(); i++){
if(edges[index][i] > 0)
return i;
}
return -1;
}
}