使用Dijkstra算法找到最短路线

编程入门 行业动态 更新时间:2024-10-12 12:34:50
本文介绍了使用Dijkstra算法找到最短路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要找到一个图形的2个顶点之间的最短路径。我有一个矩阵,其中包含所有权重。我该怎么做?目前,我有以下代码:

I need to find the shortest route between 2 vertices of a graph. I have a matrix, which contains all the weights. How can I do it? Currently, I have the following code:

private int[] Dijkstra(int start, int end) { bool[] done = new bool[8]; int[] parent = new int[8]; for (int i = 0; i < parent.Length; i++) parent[i] = -1; int[] distances = new int[8]; for (int i = 0; i < distances.Length; i++) distances[i] = int.MaxValue; distances[start] = 0; int current = start; while (!done[current]) { done[current] = true; for (int i = 0; i < 8; i++) { if (graph[current, i] != int.MaxValue) { int dist = graph[current, i] + distances[current]; if (dist < distances[i]) { distances[i] = dist; parent[i] = current; } } } int min = int.MaxValue; for (int i = 0; i < 8; i++) { if (distances[i] < min&&!done[i]) { current = i; min = distances[i]; } } } return parent; }

它有效,但是我不知道如何找到它最短的路线,例如1和3之间的路线,返回的路线类似于1 => 4 => 2 => 3。 预先感谢。

It works, but, however I don't know how to make it find the shortest route between, for example 1 and 3, and return the route like 1=>4=>2=>3. Thanks in advance.

推荐答案

Djikstra的算法使用父数组来跟踪从头到尾的最短路径。您将从parent [end]开始,然后按照数组的条目进行操作,直到重新开始。

Djikstra's Algorithm uses the parent array to track the shortest path from start to end. You'd start at parent[end] and follow the entries of the array until you got back to start.

某些伪代码:

List<int> shortestPath = new List<int>(); int current = end; while( current != start ) { shortestPath.Add( current ); current = parent[current]; } shortestPath.Reverse();

您唯一需要担心的问题是是否传递了起始值和结束值in是适当的值(例如,它们是否实际上代表图形中的顶点)。

Only thing you worry have to worry about with your function is whether or not the start and end values passed in are appropriate values (whether or not they actually represent vertices in your graph, for example ).

更多推荐

使用Dijkstra算法找到最短路线

本文发布于:2023-11-30 15:58:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650603.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:最短   算法   路线   Dijkstra

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!