C#实现最短路径算法

 创建点集

            double r = 200 * 500;
            double width = 1920;
            double height = 1080;

            int col = (int)(r / width);
            int row = (int)(r / height);
            List<(double, double)> list1 = new List<(double, double)>();
            for (int i = 0; i < row; ++i)
            {
                var y = i * height;
                if (y < r)
                {
                    var xxx = Math.Sqrt(r * r - y * y);
                    var x = xxx - (xxx % width);
                    list1.Add((x, y));
                    list1.Add((-x, y));
                    list1.Add((x, -y));
                    list1.Add((-x, -y));
                }
            }

 点阵像这样一样

最短路径算法,使用LinkedList返回,后续对插入友好

  LinkedList<(double, double)> NearestNeighborTSP(List<(double, double)> points)
        {
            int n = points.Count;
            bool[] visited = new bool[n];
            visited[0] = true;
            int current = 0;
            LinkedList<(double, double)> path = new LinkedList<(double, double)>();
            path.AddLast(points[current]);

            for (int i = 1; i < n; i++)
            {
                double minDistance = double.MaxValue;
                int next = -1;

                for (int j = 0; j < n; j++)
                {
                    if (!visited[j])
                    {
                        double dist = Distance(points[current], points[j]);
                        if (dist < minDistance)
                        {
                            minDistance = dist;
                            next = j;
                        }
                    }
                }

                current = next;
                visited[current] = true;
                path.AddLast(points[current]);
            }

            path.AddLast(points[0]);

            return path;
        }

        double Distance((double, double) point1, (double, double) point2)
        {
            return Math.Sqrt(Math.Pow(point1.Item1 - point2.Item1, 2) + Math.Pow(point1.Item2 - point2.Item2, 2));
        }

 路径找完之后(局部展示图,斜线连起来的)

 矫正斜线

            var currentNode = res.First;
            while (currentNode != null && currentNode.Next != null)
            {
                var nextNode = currentNode.Next;
                if (currentNode.Value.Item1 != nextNode.Value.Item1 && currentNode.Value.Item2 != nextNode.Value.Item2)
                {
                    var tempX = Math.Min(currentNode.Value.Item1, nextNode.Value.Item1);
                    var tempY = currentNode.Value.Item1 > nextNode.Value.Item1 ? currentNode.Value.Item2 : nextNode.Value.Item2;
                    res.AddAfter(currentNode, (tempX, tempY));
                    currentNode = nextNode; // Skip the inserted node
                }
                else
                    currentNode = currentNode.Next;
            }

矫正后效果

完整测试代码(demo中所用WPF框架,图表控件为ScottPlot5,nuget里直接搜,装5.0以上版本):

public void test()
        {

            double r = 200 * 500;
            double width = 1920;
            double height = 1080;

            int col = (int)(r / width);
            int row = (int)(r / height);
            List<(double, double)> list1 = new List<(double, double)>();
            for (int i = 0; i < row; ++i)
            {
                var y = i * height;
                if (y < r)
                {
                    var xxx = Math.Sqrt(r * r - y * y);
                    var x = xxx - (xxx % width);
                    list1.Add((x, y));
                    list1.Add((-x, y));
                    list1.Add((x, -y));
                    list1.Add((-x, -y));
                }
            }
            var wpfPlot = new ScottPlot.WPF.WpfPlot();
            var xs = list1.Select(x => x.Item1).ToArray();
            var ys = list1.Select(y => y.Item2).ToArray();
            var xx = wpfPlot.Plot.Add.Scatter(xs, ys, ScottPlot.Colors.Red).LineWidth = 0;
            var res = NearestNeighborTSP(list1);
            var currentNode = res.First;
            while (currentNode != null && currentNode.Next != null)
            {
                var nextNode = currentNode.Next;
                if (currentNode.Value.Item1 != nextNode.Value.Item1 && currentNode.Value.Item2 != nextNode.Value.Item2)
                {
                    var tempX = Math.Min(currentNode.Value.Item1, nextNode.Value.Item1);
                    var tempY = currentNode.Value.Item1 > nextNode.Value.Item1 ? currentNode.Value.Item2 : nextNode.Value.Item2;
                    res.AddAfter(currentNode, (tempX, tempY));
                    currentNode = nextNode; // Skip the inserted node
                }
                else
                    currentNode = currentNode.Next;
            }

            var xs2 = res.Select(x => x.Item1).ToArray();
            var ys2 = res.Select(x => x.Item2).ToArray();
            var yy = wpfPlot.Plot.Add.Scatter(xs2, ys2, ScottPlot.Colors.Blue).LineWidth = 1;
            grid.Children.Add(wpfPlot);
        }


        LinkedList<(double, double)> NearestNeighborTSP(List<(double, double)> points)
        {
            int n = points.Count;
            bool[] visited = new bool[n];
            visited[0] = true;
            int current = 0;
            LinkedList<(double, double)> path = new LinkedList<(double, double)>();
            path.AddLast(points[current]);

            for (int i = 1; i < n; i++)
            {
                double minDistance = double.MaxValue;
                int next = -1;

                for (int j = 0; j < n; j++)
                {
                    if (!visited[j])
                    {
                        double dist = Distance(points[current], points[j]);
                        if (dist < minDistance)
                        {
                            minDistance = dist;
                            next = j;
                        }
                    }
                }

                current = next;
                visited[current] = true;
                path.AddLast(points[current]);
            }

            path.AddLast(points[0]);

            return path;
        }

        double Distance((double, double) point1, (double, double) point2)
        {
            return Math.Sqrt(Math.Pow(point1.Item1 - point2.Item1, 2) + Math.Pow(point1.Item2 - point2.Item2, 2));
        }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#实现路径算法的方式有很多种,其中比较常用的是Dijkstra算法和A*算法。下面我给你介绍一下这两种算法实现方式。 1. Dijkstra算法 Dijkstra算法是一种经典的最路径算法,它可以求解带权有向图中的单源最路径问题。具体实现步骤如下: (1)初始化:将起点s加入集合S,将所有与s直接相连的点加入集合T。 (2)选择最路径:从T中选择一个到s距离最的点v,并将v加入集合S。 (3)更新距离:对于T中的每个点w,如果从s到v再到w的距离比从s到w的距离更,则更新从s到w的距离。 (4)重复执行步骤2和步骤3,直到T为空。 下面是C#代码实现: ``` public static void Dijkstra(int[,] graph, int start) { int n = graph.GetLength(0); int[] dist = new int[n]; bool[] visited = new bool[n]; for (int i = 0; i < n; i++) { dist[i] = int.MaxValue; visited[i] = false; } dist[start] = 0; for (int count = 0; count < n - 1; count++) { int u = -1; for (int i = 0; i < n; i++) { if (!visited[i] && (u == -1 || dist[i] < dist[u])) { u = i; } } visited[u] = true; for (int v = 0; v < n; v++) { if (graph[u, v] != 0 && !visited[v]) { int alt = dist[u] + graph[u, v]; if (alt < dist[v]) { dist[v] = alt; } } } } } ``` 2. A*算法 A*算法是一种启发式搜索算法,它可以在带权有向图中找到从起点到终点的最路径。具体实现步骤如下: (1)初始化:将起点加入open列表,将起点的f值设为0。 (2)选择节点:从open列表中选择f值最小的节点作为当前节点,并将其从open列表中移除,加入close列表。 (3)扩展节点:对于当前节点的每个邻居节点,计算其g值和h值,并计算出f值。如果该节点不在open列表和close列表中,则将其加入open列表。 (4)重复执行步骤2和步骤3,直到当前节点为终点或者open列表为空。 下面是C#代码实现: ``` public static void AStar(int[,] graph, int start, int end) { int n = graph.GetLength(0); int[] g = new int[n]; int[] h = new int[n]; int[] f = new int[n]; int[] parent = new int[n]; bool[] open = new bool[n]; bool[] close = new bool[n]; for (int i = 0; i < n; i++) { g[i] = int.MaxValue; h[i] = Heuristic(graph, i, end); f[i] = int.MaxValue; parent[i] = -1; open[i] = false; close[i] = false; } g[start] = 0; f[start] = h[start]; open[start] = true; while (true) { int u = -1; for (int i = 0; i < n; i++) { if (open[i] && (u == -1 || f[i] < f[u])) { u = i; } } if (u == -1) { break; } if (u == end) { break; } open[u] = false; close[u] = true; for (int v = 0; v < n; v++) { if (graph[u, v] != 0 && !close[v]) { int alt = g[u] + graph[u, v]; if (alt < g[v]) { g[v] = alt; f[v] = g[v] + h[v]; parent[v] = u; if (!open[v]) { open[v] = true; } } } } } } private static int Heuristic(int[,] graph, int start, int end) { return Math.Abs(start / graph.GetLength(1) - end / graph.GetLength(1)) + Math.Abs(start % graph.GetLength(1) - end % graph.GetLength(1)); } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值