图论的相关算法java实现

本文深入探讨了图论在Java编程中的应用,详细讲解了几种核心算法的实现,包括深度优先搜索(DFS)、广度优先搜索(BFS)、最小生成树(MST)如Prim算法和Kruskal算法,以及最短路径算法如Dijkstra算法和Floyd算法。通过实例解析,帮助读者掌握如何在实际问题中运用这些算法。
摘要由CSDN通过智能技术生成
package Graph;
import java.util.ArrayList;
import java.util.LinkedList;
import DataStruct.Union;
import Sort.Sort;

/**
     图类 
     构造函数封装了将邻接矩阵转化临接表的方法,提供了拓扑排序,无权最短路径算法等
     所有算法都是基于临接表(拓扑排序 基于入度数组,入度数组也是基于临接表求得)
 */
public class Graph {
   
    public static final int INFINITY=-1;//代表不相连 无穷
    /**
     图的顶点
     */
    class Vertex{
        int topnum;
        Edge edge=null;

        //下面三条信息是为了搜索最短路径
        int dis=INFINITY;
        boolean arrived=false;
        Vertex path=null;

        public Vertex(int topnum) {
            this.topnum = topnum;
        }
        public Vertex(int topnum,Edge edge) {
            this.topnum = topnum;
            this.edge=edge;
        }
    }
    /**
     图的边(用于临接表)
     */
    class Edge{
        int adjacentTop;//边邻接的顶点 1->2  adjacentTop为2
        int weight = 1;     //连接两顶点的边的权值
        Edge next;
        public Edge(int adjacentTop,int weight) {
            this.adjacentTop = adjacentTop;
            this.next = null;
            this.weight=weight;
        }
    }
    class Side implements Comparable<Side>{
        int from;
        int to;
        int weight;
        public Side(int from, int to, int weight) {
            this.from = from;
            this.to = to;
            this.weight = weight;
        }
        public int compareTo(Side arg0) {
            return weight>((Side)arg0).weight? 1:weight==((Side)arg0).weight? 0:-1;
        }
    }
    private int numVertexs;//顶点数
    private int numEdges=0;//边数
    private Vertex[] NodeTable=null;//邻接表
    private int[] InDegreeList;//入度数组  数组从第一个顶点(下标为零)表示入度的边数
    /**
     * 边的集合 初始化Graph对象时 自动初始化
     */
    private ArrayList<Side> sides=new ArrayList<Graph.Side>();
    public Graph(int[][] AdjacencyMatrix) {
        this.numVertexs = AdjacencyMatrix.length;
        NodeTableInit(numVertexs);
        InDegreeList=new int[numVertexs];
        MatrixToList(AdjacencyMatrix);
    }
    /**
     * @param length
     * 邻接表初始化 边暂时都为空
     */
    
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值