这是一个学校项目;我遇到了很多麻烦,我似乎找不到可以理解的解决方案。
a b c d e z
a - 2 3 - - -
b 2 - - 5 2 -
c 3 - - - 5 -
d - 5 - - 1 2
e - 2 5 1 - 4
z - - - 2 4 -
那就是二维数组。因此,如果您想找到最短路径,它从 a,b,e,d,z = 7 和 (a,b) = (b,a) 开始 - 它会将您带到新行以获取该行的相邻行路径
有没有人可以帮我实现这个例子的 Dijkstra 算法?我真的很感激。(我似乎最喜欢数组,地图和集合让我有点困惑,列表是可管理的——尽管我现在愿意研究任何类型的解决方案)
[至少我不只是从网络上抄袭来源。我真的很想学习这些东西......这真的很难(>.<)]
哦,起点是A,终点是Z
和大多数人一样,我认为算法的概念并不难——我只是可以看到正确的编码......请帮忙?
示例代码——一个朋友帮了我很多(尽管它充满了我发现难以理解的数据结构)我也尝试过调整来自 dreamincode.net/forums/blog/martyr2/index.php 的 C++ 代码? showentry = 578 进入java,但这并不顺利......
import java.util.*;
public class Pathy{
private static class pathyNode{
public final String name;
public Map<pathyNode, Integer> adjacentNodes;
public pathyNode(String n){
name = n;
adjacentNodes = new HashMap<pathyNode, Integer>();
}
}
//instance variables
//constructors
//accessors
//methods
public static ArrayList<pathyNode> convert(int[][] inMatrix){
ArrayList<pathyNode> nodeList = new ArrayList<pathyNode>();
for(int i = 0; i < inMatrix.length; i++){
nodeList.add(new pathyNode("" + i));
}
for(int i = 0; i < inMatrix.length; i++){
for(int j = 0; j < inMatrix[i].length; j++){
if(inMatrix[i][j] != -1){
nodeList.get(i).adjacentNodes.put(nodeList.get(j),
new Integer(inMatrix[i][j]));
}
}
}
return nodeList;
}
public static Map<pathyNode, Integer> Dijkstra(ArrayList<pathyNode> inGraph){
Set<pathyNode> visited = new HashSet<pathyNode>();
visited.add(inGraph.get(0));
pathyNode source = inGraph.get(0);
Map answer = new TreeMap<pathyNode, Integer>();
for(pathyNode node : inGraph){
dijkstraHelper(visited, 0, source, node);
answer.put(node, dijkstraHelper(visited, 0, source, node));
}
return answer;
}
private static int dijkstraHelper(Set<pathyNode> visited, int sum, pathyNode start, pathyNode destination){
Map<pathyNode, Integer> adjacent = new HashMap<pathyNode, Integer>();
for(pathyNode n : visited){
for(pathyNode m: n.adjacentNodes.keySet()){
if(adjacent.containsKey(m)){
Integer temp = n.adjacentNodes.get(m);
if(temp < adjacent.get(m)){
adjacent.put(m, temp);
}
}
else{
adjacent.put(m, n.adjacentNodes.get(m));
}
}
}
Map<pathyNode, Integer> adjacent2 = new HashMap<pathyNode, Integer>();
Set<pathyNode> tempSet = adjacent.keySet();
tempSet.removeAll(visited);
for(pathyNode n: tempSet){
adjacent2.put(n, adjacent.get(n));
}
adjacent = adjacent2;
Integer min = new Integer(java.lang.Integer.MAX_VALUE);
pathyNode minNode = null;
for(pathyNode n: adjacent.keySet()){
Integer temp = adjacent.get(n);
if(temp < min){
min = temp;
minNode = n;
}
}
visited.add(minNode);
sum += min.intValue();
sum = dijkstraHelper(visited, sum, start, destination);
return sum;
}
//main
public static void main(String[] args){
int[][] input = new int[][] { {-1, 2, 3, -1, -1, -1},
{2, -1, -1, 5, 2, -1},
{3, -1, -1, -1, 5, -1},
{-1, 5, -1, -1, 1, 2},
{-1, 2, 5, 1, -1, 4},
{-1, -1, -1, 2, 4, -1},
};
//-1 represents an non-existant path
System.out.println(Dijkstra(convert(input)));
}
}