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
* 邻接表初始化 边暂时都为空
*/
图论的相关算法java实现
最新推荐文章于 2023-12-09 15:15:27 发布
本文深入探讨了图论在Java编程中的应用,详细讲解了几种核心算法的实现,包括深度优先搜索(DFS)、广度优先搜索(BFS)、最小生成树(MST)如Prim算法和Kruskal算法,以及最短路径算法如Dijkstra算法和Floyd算法。通过实例解析,帮助读者掌握如何在实际问题中运用这些算法。
摘要由CSDN通过智能技术生成