我正在实现一个最短路径算法来处理我的图表,但是我遇到了困难。在此之前,有很多帖子涵盖了要使用哪个算法,但没有涉及到这么基础的问题。我认为我已经实现了这个问题中的代码。对于每个被遍历的节点,我都会存储一个数组表示我从哪里来。 我不知道如何通过堆栈找到最短路径。
我有以下节点:
我的顶点列表是:
东京,夏威夷,旧金山,洛杉矶,圣地亚哥,芝加哥,纽约,迈阿密,伦敦
寻找从伦敦到夏威夷的路径,我的堆栈看起来像:
000000000 000400000 101100000 033033000 020202000 005500550 000007707 000006066 000000880
一些节点被链接到了圣地亚哥,但其他节点(我想)看起来是正确的。下面是我的实现方式,但我不知道如何通过堆栈并追踪回去。 下面的代码输出路径:夏威夷,夏威夷,夏威夷。它是错误的。
我有以下节点:
![enter image description here](https://istack.dev59.com/FNtxB.webp)
东京,夏威夷,旧金山,洛杉矶,圣地亚哥,芝加哥,纽约,迈阿密,伦敦
寻找从伦敦到夏威夷的路径,我的堆栈看起来像:
000000000 000400000 101100000 033033000 020202000 005500550 000007707 000006066 000000880
一些节点被链接到了圣地亚哥,但其他节点(我想)看起来是正确的。下面是我的实现方式,但我不知道如何通过堆栈并追踪回去。 下面的代码输出路径:夏威夷,夏威夷,夏威夷。它是错误的。
public static List<string> ShortestPath(Graph graph, string src, string dest)
{
List<string> path = new List<string>();
List<string> city_ref = graph.GetVertices();
Queue<string> Visited = new Queue<string>();
Queue<string> ToVisit = new Queue<string>();
Stack<int[]> stack = new Stack<int[]>();
ToVisit.Enqueue(src);
while (ToVisit.Count != 0)
{
string V = ToVisit.Dequeue();
if (Visited.Contains(V))
;
else
{
int[] previous = new int[city_ref.Count];
for (int i = 0; i < graph.Neighbors(V).Count; i++)
{
//previous[i] = -1;
ToVisit.Enqueue(graph.Neighbors(V)[i]);
int pointer = city_ref.IndexOf(graph.Neighbors(V)[i]);
previous[pointer] = city_ref.IndexOf(V);
}
stack.Push(previous);
Visited.Enqueue(V);
}
}
int path_val = city_ref.IndexOf(dest);
while(stack.Count != 0)
{
int[] i = stack.Pop();
for (int p = 0; p < i.Length; p++)
{
if (i[p] == path_val)
{
path.Add(city_ref[i[p]]);
path_val = i[p];
}
}
}
return path;
}