1.邻接矩阵来实现带权图结构
package com.upupgogogo;
/**
* Created by upupgogogo on 2018/3/26.上午11:45
*/
public class AdjMatrixGraph<T> {
protected SeqList<T> vertexlist; //顺序表储存图的定点集合
protected int[][] adjmatrix; //图的邻接矩阵
private final int MAX_WEIGHT = 99999; //最大权值(表示无穷大)
public AdjMatrixGraph(int size){
size = size < 10 ? 10 : size;
this.vertexlist = new SeqList<>(size); //构造容量为size的空顺序表,当前定点数为0
this.adjmatrix = new int[size][size]; //初始化邻接矩阵
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
this.adjmatrix[i][j] = (i == j) ? 0 : MAX_WEIGHT;
}
public AdjMatrixGraph(T[] vertexlist, Edge[] edges){
this(vertexlist.length);
if (vertexlist == null)
return;
for (int i = 0; i < vertexlist.length; i++)
insertVertex(vertexlist[i]);
if (edges != null)
for (int j = 0; j < edges.length; j++)
insertEdge(edges[j]);
}
//返回顶点数
public int vertexCount(){return this.vertexlist.length();}
//返回顶点vi的数据元素
public T get(int i){ return this.vertexlist.get(i);}
//返回<vi,vj>边的权值
public int getWeight(int i, int j){
return this.adjmatrix[i][j];
}
public void checkIndex(int i, int j){
if (i > this.vertexCount() || i < 0 || j > this.vertexCount() || j < 0)
throw new IndexOutOfBoundsException("size ="+this.vertexCount());
}
//新增一个顶点
public int insertVertex(T x){
//顺序表自动扩容
this.vertexlist.add(x);
//二维数组判断是否扩容
if (this.vertexCount() > this.adjmatrix.length){
int[][] temp = this.adjmatrix;
adjmatrix = new int[temp.length*2][temp.length*2];
for (int i = 0; i < temp.length; i++){
for (int j = 0; j < temp.length; j++)
this.adjmatrix[i][j] = temp[i][j];
for (int j = temp.length; j < temp.length*2; j++)
this.adjmatri