【问题标题】:Using a stack to find shortest path in breadth first search使用堆栈在广度优先搜索中找到最短路径
【发布时间】:2013-11-17 22:46:09
【问题描述】:

我很难为我的图表实现最短路径算法。很多关于这个算法的帖子都涵盖了使用哪种算法,但没有什么是基本的。我想我已经实现了the code from this question. 对于遍历的每个节点,我存储了一个数组来指示我来自哪里。我不确定如何通过堆栈找到最短路径。

我有以下节点:

我的顶点列表是:

东京、夏威夷、旧金山、洛杉矶、圣地亚哥、芝加哥、纽约、迈阿密、伦敦

寻找从伦敦到夏威夷的路径,我的堆栈最终看起来像:
000000000
000400000
101100000
033033000
020202000
005500550
000007707
000006066
000000880

不知何故东京与圣地亚哥联系在一起,但其余的(我认为)看起来是正确的。下面是我的实现,但我不知道如何遍历堆栈并追溯我的方式。下面的代码输出路径:hawaii, hawaii, hawaii。错了。

 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;
    }

【问题讨论】:

  • BFS 实际上与队列一起工作。您可以查看 bfs 的任何基本代码以清楚地理解它。堆栈图以深度优先方式遍历,实际上并不能确保最短路径。
  • 哦,对于加权图(所有边的权重不同)bfs 将不起作用。改为实现 Dijkstra 算法。
  • @Fallen 实际上 Dijkstra 找到了从选定节点到所有节点的最短路径;只是想要单对开始-结束之间的路径-但实际上想法几乎相同。
  • 现在,我只是忽略了权重。我不认为我可以使用 bfs 队列来找到最短路径?我如何追踪我去过的地方?

标签: c# algorithm graph shortest-path breadth-first-search


【解决方案1】:

我建议你从wikipedia 实现算法。当你找到从起点到终点的所有路径时,尝试向后遍历,比较节点 X 与其邻居之间的距离。你也可以看看here。希望对您有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-06
    • 1970-01-01
    • 2018-12-25
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 1970-01-01
    • 2011-05-23
    相关资源
    最近更新 更多