无权最短路径算法java实现
- 无权最短路径算法方法实现
- 完整代码
代码
路径扫描
public static void unweight(Graph s) {
Queue<Graph> q = new LinkedList<Graph>();
s.dist = 0;
q.add(s);
while (q.size() != 0) {
Graph start = q.poll();
for (Graph sadj : start.adj) {
if (sadj.dist == INFINITY) {
sadj.dist = start.dist + 1;
sadj.latest = start;
q.add(sadj);
}
}
}
}
从源点开始更新:
将源点的距离设为0,然后入队;搜索源点临近点,判断该点是否被扫描,如果没有被扫描,则将距离设为源点距离+1,并将源点设为该点上一节点。
重复该过程,直至所有点被扫描到。
通过路径扫描得到节点之间的关系以及距离。
路径打印
private static void printPath(String graphname) {
Graph graph = find(graphname);
if (graph.latest != null) {
printPath(graph.latest.name);
System.out.print("to");
}
System.out.println(graph.name);
}
在通过路径扫描得到节点关系的基础上,采用递归进行路径打印,递归最里层为源点,依次往外打印指定的节点。
完整代码
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class DirectionShortDistance {
public static final int INFINITY = Integer.MAX_VALUE;
public static List<Graph> graphmap = new LinkedList<Graph>();
static class Graph {
public String name;
public int dist;
public LinkedList<Graph> adj = new LinkedList<Graph>();
public Graph latest;
public Graph(String name) {
this.name = name;
}
}
public static void unweight(Graph s) {
Queue<Graph> q = new LinkedList<Graph>();
s.dist = 0;
while (q.size() != 0) {
Graph start = q.poll();
for (Graph sadj : start.adj) {
if (sadj.dist == INFINITY) {
sadj.dist = start.dist + 1;
sadj.latest = start;
q.add(sadj);
}
}
}
}
public static Graph find(String name) {
for (Graph graph : graphmap) {
if (graph.name.equals(name))
return graph;
}
return null;
}
private static void printPath(String graphname) {
Graph graph = find(graphname);
if (graph.latest != null) {
printPath(graph.latest.name);
System.out.print("to");
}
System.out.println(graph.name);
}
public static void main(String[] args) throws Exception {
Graph v1 = new Graph("v1");
Graph v2 = new Graph("v2");
Graph v3 = new Graph("v3");
Graph v4 = new Graph("v4");
Graph v5 = new Graph("v5");
Graph v6 = new Graph("v6");
Graph v7 = new Graph("v7");
graphmap.add(v1);
graphmap.add(v2);
graphmap.add(v3);
graphmap.add(v4);
graphmap.add(v5);
graphmap.add(v6);
graphmap.add(v7);
for (Graph g : graphmap) {
g.dist = INFINITY;
g.latest = null;
}
v1.adj.add(v2);
v1.adj.add(v4);
v2.adj.add(v4);
v2.adj.add(v5);
v3.adj.add(v1);
v3.adj.add(v6);
v4.adj.add(v3);
v4.adj.add(v5);
v4.adj.add(v6);
v4.adj.add(v7);
v5.adj.add(v7);
v7.adj.add(v6);
List<Graph> vs = new ArrayList<Graph>();
vs.add(v1);
vs.add(v2);
vs.add(v3);
vs.add(v4);
vs.add(v5);
vs.add(v6);
vs.add(v7);
unweight(v3);
System.out.println("The shortest path from v3:");
for (int i = 1; i <= 7; i++) {
printPath("v" + i);
}
}
}