1、图类基本组成

存储在邻接表中的基本项

 /**
* Represents an edge in the graph
*
*/
class Edge implements Comparable<Edge> {
public Vertex dest;  //Second vertex in Edge
public double cost;  //Edge cost public Edge(Vertex d, double c) {
dest = d;
cost = c;
} @Override
public int compareTo(Edge o) {
double otherCost = o.cost;
return cost < otherCost ? -1 : cost > otherCost ? 1 : 0;
} @Override
public String toString() {
return "Edge{" + "dest=" + dest + ", cost=" + cost + '}';
}
}

存储每个顶点信息

 /**
* Represents a vertex in the graph
*/
class Vertex {
public String name;
public List<Edge> adj;//Adjacent vertices
public double dist;
public Vertex prev;
public int scratch;//Extra variable used in algorithm public Vertex(String name) {
this.name = name;
adj = new LinkedList<Edge>();
reset();
} public void reset() {
dist = Graph.INFINITY;
prev = null;
scratch = 0;
} @Override
public String toString() {
return "Vertex{" + "name='" + name + '\'' + ", prev=" + prev + ", adj=" + adj + ", dist=" + dist + '}';
}
}

图类的框架

 import java.util.*;

 /**
* Created by Vanguard on 2017/4/6.
*/
public class Graph {
public static final double INFINITY = Double.MAX_VALUE;
private Map<String, Vertex> vertexMap = new HashMap<String, Vertex>(); public void addEdge(String sourceName, String destName, double cost) {
Vertex v = getVertex(sourceName);
Vertex w = getVertex(destName);
v.adj.add(new Edge(w, cost));
} /**
* 通过查询图的表,打印最短路径
*
* @param destName
*/
public void printPath(String destName) {
Vertex w = vertexMap.get(destName);
if (w == null) {
System.out.println("NoSuchElementException");
return;
} else if (w.dist == INFINITY) {
System.out.println(destName + " is unreachable.");
} else {
System.out.print("(Cost is: " + w.dist + ") ");
printPath(w);
System.out.println();
}
} private void printPath(Vertex dest) {
if (dest.prev != null) {
printPath(dest.prev);
System.out.print(" --> ");
}
System.out.print(dest.name);
} private Vertex getVertex(String vertexName) {
Vertex v = vertexMap.get(vertexName);
if (v == null) { //create if not exist.
v = new Vertex(vertexName);
vertexMap.put(vertexName, v);
}
return v;
} private void clearAll() {
for (Vertex v : vertexMap.values()) {
v.reset();
}
}
}

2、最短路径算法

广度优先搜索

 /**
* Single-source unweighted shortest-path algorithm.
* 无权单源最短路径算法——广度优先搜索
*
* @param startName
*/
public void unweighted(String startName) {
clearAll();
Vertex start = vertexMap.get(startName);
if (start == null) {
throw new NoSuchElementException("Start vertex not fond.");
}
Queue<Vertex> q = new LinkedList<Vertex>();
q.add(start);
start.dist = 0;
while (!q.isEmpty()) {
Vertex v = q.remove();
for (Edge e : v.adj) {
Vertex w = e.dest;
if (w.dist == INFINITY) {
w.dist = v.dist + 1;
w.prev = v;
q.add(w);
}
}
}
}

Dijstra算法

 /**
* Single-source unweighted shortest-path algorithm.
* 无权单源最短路径算法——广度优先搜索
*
* @param startName
*/
public void unweighted(String startName) {
clearAll();
Vertex start = vertexMap.get(startName);
if (start == null) {
throw new NoSuchElementException("Start vertex not fond.");
}
Queue<Vertex> q = new LinkedList<Vertex>();
q.add(start);
start.dist = 0;
while (!q.isEmpty()) {
Vertex v = q.remove();
for (Edge e : v.adj) {
Vertex w = e.dest;
if (w.dist == INFINITY) {
w.dist = v.dist + 1;
w.prev = v;
q.add(w);
}
}
}
}

带负权值得最短路径算法

 /**
* Single-source negative-weighted shortest-path algorithm.
* 带负权值得最短路径算法
*
* @param startName
*/
public void negative(String startName) {
clearAll(); Vertex start = vertexMap.get(startName);
if (start == null) {
throw new NoSuchElementException("Start vertex not fond.");
}
Queue<Vertex> q = new LinkedList<>();
q.add(start);
start.dist = 0;
start.scratch++;
while (!q.isEmpty()) {
Vertex v = q.remove();
if (v.scratch++ > 2 * vertexMap.size()) {
System.out.println("Negative cycle detected.");
}
for (Edge e : v.adj) {
Vertex w = e.dest;
double costvw = e.cost;
if (w.dist > v.dist + costvw) {
w.dist = v.dist + costvw;
w.prev = v;
//Enqueue only if not already on the queue
if (w.scratch++ % 2 == 0)
q.add(w);
else
w.scratch--;
}
} }
}

THE END.

图之单源Dijkstra算法、带负权值最短路径算法的更多相关文章

  1. Expm 10_1 带负权值边的有向图中的最短路径问题

    [问题描述] 对于一个带负权值边的有向图,实现Bellman-Ford算法,求出从指定顶点s到其余顶点的最短路径,并判断图中是否存在负环. package org.xiu68.exp.exp10; p ...

  2. 非负权值有向图上的单源最短路径算法之Dijkstra算法

    问题的提法是:给定一个没有负权值的有向图和其中一个点src作为源点(source),求从点src到其余个点的最短路径及路径长度.求解该问题的算法一般为Dijkstra算法. 假设图顶点个数为n,则针对 ...

  3. Wormholes 最短路判断有无负权值

    Description While exploring his many farms, Farmer John has discovered a number of amazing wormholes ...

  4. poj 3259 Wormholes 判断负权值回路

    Wormholes Time Limit: 2000 MS Memory Limit: 65536 KB 64-bit integer IO format: %I64d , %I64u   Java ...

  5. SPFA 最短路 带负权边的---- 粗了解

    SPFA(Shortest Path Faster Algorithm)是Bellman-Ford算法的一种队列实现,减少了不必要的冗余计算. 算法大致流程是用一个队列来进行维护. 初始时将源加入队列 ...

  6. Bellman-Ford算法——解决负权边

    Dijkstra算法虽然好,但是它不能解决带有负权边(边的权值为负数)的图. 接下来学习一种无论在思想上还是在代码实现上都可以称为完美的最短路径算法:Bellman-Ford算法. Bellman-F ...

  7. POJ-2195 Going Home---KM算法求最小权值匹配(存负边)

    题目链接: https://vjudge.net/problem/POJ-2195 题目大意: 给定一个N*M的地图,地图上有若干个man和house,且man与house的数量一致.man每移动一格 ...

  8. 分布式技术专题-分布式协议算法-带你彻底认识Paxos算法、Zab协议和Raft协议的原理和本质

    内容简介指南 Paxo算法指南 Zab算法指南 Raft算法指南 Paxo算法指南 Paxos算法的背景 [Paxos算法]是莱斯利·兰伯特(Leslie Lamport)1990年提出的一种基于消息 ...

  9. 理解KNN算法中的k值-knn算法中的k到底指的是什么 ?

    2019-11-09 20:11:26为方便自己收藏学习,转载博文from:https://blog.csdn.net/llhwx/article/details/102652798 knn算法是指对 ...

随机推荐

  1. R语言包的安装

    pheatmap包的安装 1: 首先R语言的安装路径里面最好不要有中文路径 2: 在安装其他依存的scales和colorspace包时候要关闭防火墙 错误提示: 试开URL'https://mirr ...

  2. JAVA浮点数计算精度损失底层原理与解决方案

    浮点数会有精度损失这个在上大学的时候就已经被告知,但是至今完全没有想明白其中的原由,老师讲的时候也是一笔带过的,自己也没有好好琢磨.终于在工作的时候碰到了,于是google了一番. 问题: 对两个do ...

  3. Linux 格式化和挂载数据盘

    如果您已经为 ECS 实例配了数据盘,您需要先格式化数据盘并挂载文件系统后才能正常使用数据盘. 注意: 磁盘分区和格式化是高风险行为,请慎重操作.本文档描述如何处理一个新买的数据盘,如果您的数据盘上有 ...

  4. 【Learning】 欧拉回路的求解

    欧拉回路: 欧拉回路,俗称一笔画,比如一笔画五角星等. 这里给出非严谨的定义:欧拉回路即从一个点出发,不重复.不遗漏地经过所有的边与所有的点,并恰好回到出发点. 包含欧拉回路的图称为欧拉图. 欧拉回路 ...

  5. python 循环语句 函数 模块

    python循环语句 while循环语法结构 当需要语句不断的重复执行时,可以使用while循环 while expression: while_suite 语句ehile_suite会被连续不断的循 ...

  6. 整理几个js上传多张图片的效果

    一.普通的上传图片,张数不限制 <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8"&g ...

  7. Ubuntu 卸载cario-dock

    偶然间听说别人用dock 可以把ubuntu美化,结果就装了个cairo-dock .结果是苹果mac的风格.不是很喜欢.于是就卸载,卸载过程中.发行卸载不掉. 尝试了很多方法. sudo apt-g ...

  8. FusionCharts中图的属性的总结归纳

    FusionCharts中图的属性的总结归纳 1.横坐标label间隔显示 labelStep="4" 2.柱状图有椭圆角 useRoundEdges="1"

  9. The struts dispatcher cannot be found

    1.错误描述 严重:Servlet.service() for servlet jsp threw exception The struts dispatcher cannot be found.Th ...

  10. Axure使用心得分享

    因为之前很少涉及到原型设计,所以对这个原型设计工具也不太熟悉,第一次使用走了不少的弯路,在这里把自己在使用过程中的心得跟大家分享一下,希望能够对大家有所帮助. 一. 元素的选择 我觉得这是Axure原 ...