邻接矩阵来实现带权图结构,并通过Dijkstra算法寻找最短路径

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
  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值