首页 > 编程语言 >最短路径算法-迪杰斯特拉(Dijkstra)算法在c#中的实现和生产应用

最短路径算法-迪杰斯特拉(Dijkstra)算法在c#中的实现和生产应用

时间:2022-08-30 10:57:27浏览次数:91  
标签:Weight c# double 迪杰 算法 Nodes var nodes public

迪杰斯特拉(Dijkstra)算法是典型最短路径算法,用于计算一个节点到其他节点的最短路径。
它的主要特点是以起始点为中心向外层层扩展(广度优先遍历思想),直到扩展到终点为止

贪心算法(Greedy Algorithm)

贪心算法,又名贪婪法,是寻找最优解问题的常用方法,这种方法模式一般将求解过程分成若干个步骤,但每个步骤都应用贪心原则,选取当前状态下最好/最优的选择(局部最有利的选择),并以此希望最后堆叠出的结果也是最好/最优的解。

Dijkstra推导过程(摘自:https://zhuanlan.zhihu.com/p/346558578)

  • 通过Dijkstra计算图G中的最短路径时,需要指定一个起点D(即从顶点D开始计算)。
  • 此外,引进两个数组S和U。S的作用是记录已求出最短路径的顶点(以及相应的最短路径长度),而U则是记录还未求出最短路径的顶点(以及该顶点到起点D的距离)。
  • 初始时,数组S中只有起点D;数组U中是除起点D之外的顶点,并且数组U中记录各顶点到起点D的距离。如果顶点与起点D不相邻,距离为无穷大。
  • 然后,从数组U中找出路径最短的顶点K,并将其加入到数组S中;同时,从数组U中移除顶点K。接着,更新数组U中的各顶点到起点D的距离。
  • 重复第4步操作,直到遍历完所有顶点。

图解(摘自:https://zhuanlan.zhihu.com/p/346558578)

image

当我们理解了算法原理后,我们需要明白Dijkstra不能够处理的场景

  • 不能处理负权重边(往往找错最短路径,在Dijkstra看来,cost是递增的)
  • A-A的绕圈路径查找(需要特殊处理)

代码实战(已经在生产使用)

  • 节点对象定义:
public class Edge
    {
        public int StartNodeID;
        public int EndNodeID;
        public double Weight;
    }
public class Node
    {
        public int Id { get; set; }
        public bool Enable { get; set; }
    }
public class NodeItem
        {
            public bool Used { get; set; }
            public List<int> Nodes { get; } = new List<int>();
            public int NodeId { get; set; }
            public int Index { get; set; }
            public double Weight { get; set; }
        }
  • 初始化图,点,路径集合
public void Initialize(IEnumerable<Edge> edges, IEnumerable<Node> nodes)
        {
            _edges = edges.ToList();
            _nodes = nodes.ToList();
            _nodeItems = new List<NodeItem>();
            _graph = new double[_nodes.Count(), _nodes.Count()];
            foreach (var row in Enumerable.Range(0, _nodes.Count()))
            {
                var rowNode = _nodes[row];
                foreach (var colnum in Enumerable.Range(0, _nodes.Count()))
                {
                    if (row == colnum)
                    {
                        _graph[row, colnum] = 0;
                        continue;
                    }
                    var edge = _edges.FirstOrDefault(x =>
                            x.StartNodeID == rowNode.Id && x.EndNodeID == _nodes[colnum].Id);
                    _graph[row, colnum] = edge == null ? double.MaxValue : edge.Weight;
                }

                _nodeItems.Add(new NodeItem()
                {
                    NodeId = _nodes[row].Id,
                    Index = row,
                    Weight = double.MaxValue
                });
            }
        }
  • 路由主体方法
public Route GetRoute(int startPointID, int endPointID)
        {
            if (IsRouting)
                throw new InvalidOperationException($"can't route.router busy");

            IsRouting = true;
            Node sNode = null;
            Node dNode = null;

            try
            {
                if ((sNode = _nodes.FirstOrDefault(x => x.Id == startPointID)) == null
                    || (dNode = _nodes.FirstOrDefault(x => x.Id == endPointID)) == null)
                    throw new ArgumentNullException("can't found target points.");

                _nodeItems.FirstOrDefault(x => x.NodeId == startPointID).Used = true;
                _nodeItems.ForEach(x =>
                {
                    x.Weight = GetRowArray(_graph, _nodes.IndexOf(sNode))[x.Index];
                    x.Nodes.Add(startPointID);
                });

                while (_nodeItems.Any(x => !x.Used))
                {
                    var item = GetUnUsedAndMinNodeItem();
                    if (item == null)
                        break;

                    item.Used = true;
                    var tempRow = GetRowArray(_graph, item.Index);
                    foreach (var nodeItem in _nodeItems)
                    {
                        if (nodeItem.Weight > tempRow[nodeItem.Index] + item.Weight) 
                        {
                            nodeItem.Weight = tempRow[nodeItem.Index] + item.Weight;
                            nodeItem.Nodes.Clear();
                            nodeItem.Nodes.AddRange(item.Nodes);
                            nodeItem.Nodes.Add(item.NodeId);
                        }
                    }
                }

                var desNodeitem = _nodeItems.FirstOrDefault(x => x.NodeId == endPointID);
                if (desNodeitem.Used && desNodeitem.Weight < double.MaxValue)
                {
                    var edges = new List<Edge>();
                    foreach (var index in Enumerable.Range(0, desNodeitem.Nodes.Count - 1))
                    {
                        edges.Add(_edges.FirstOrDefault(x => x.StartNodeID == desNodeitem.Nodes[index] && x.EndNodeID == desNodeitem.Nodes[index + 1]));
                    }

                    edges.Add(_edges.FirstOrDefault(x => x.StartNodeID == desNodeitem.Nodes.Last() && x.EndNodeID == endPointID));
                    return new Route()
                    {
                        Edges = edges
                    };
                }

                return null;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                _logger.LogInformation($"startPoint:{startPointID}-endpoint:{endPointID} route faild.");
                throw;
            }
            finally
            {
                _nodeItems.ForEach(x =>
                {
                    x.Used = false;
                    x.Nodes.Clear();
                });

                IsRouting = false;
            }
        }

        private NodeItem GetUnUsedAndMinNodeItem()
        {
            return _nodeItems.Where(x => !x.Used && x.Weight != double.MaxValue).OrderBy(x => x.Weight).FirstOrDefault();
        }

        private double[] GetRowArray(double[,] source, int row)
        {
            double[] result = new double[source.GetLength(1)];
            foreach (var index in Enumerable.Range(0, result.Length))
            {
                result[index] = source[row, index];
            }

            return result;
        }

完整代码

public class DijkstraRouter
    {
        private double[,] _graph;
        private List<Edge> _edges;//所有的边
        private List<Node> _nodes;//所有的节点
        private List<NodeItem> _nodeItems;
        public bool IsRouting { get; set; }

        private readonly ILogger<DijkstraRouter> _logger;

        public DijkstraRouter(ILogger<DijkstraRouter> logger)
        {
            _logger = logger;
        }

        public Route GetRoute(int startPointID, int endPointID)
        {
            if (IsRouting)
                throw new InvalidOperationException($"can't route.router busy");

            IsRouting = true;
            Node sNode = null;
            Node dNode = null;

            try
            {
                if ((sNode = _nodes.FirstOrDefault(x => x.Id == startPointID)) == null
                    || (dNode = _nodes.FirstOrDefault(x => x.Id == endPointID)) == null)
                    throw new ArgumentNullException("can't found target points.");

                _nodeItems.FirstOrDefault(x => x.NodeId == startPointID).Used = true;
                _nodeItems.ForEach(x =>
                {
                    x.Weight = GetRowArray(_graph, _nodes.IndexOf(sNode))[x.Index];
                    x.Nodes.Add(startPointID);
                });

                while (_nodeItems.Any(x => !x.Used))
                {
                    var item = GetUnUsedAndMinNodeItem();
                    if (item == null)
                        break;

                    item.Used = true;
                    var tempRow = GetRowArray(_graph, item.Index);
                    foreach (var nodeItem in _nodeItems)
                    {
                        if (nodeItem.Weight > tempRow[nodeItem.Index] + item.Weight) 
                        {
                            nodeItem.Weight = tempRow[nodeItem.Index] + item.Weight;
                            nodeItem.Nodes.Clear();
                            nodeItem.Nodes.AddRange(item.Nodes);
                            nodeItem.Nodes.Add(item.NodeId);
                        }
                    }
                }

                var desNodeitem = _nodeItems.FirstOrDefault(x => x.NodeId == endPointID);
                if (desNodeitem.Used && desNodeitem.Weight < double.MaxValue)
                {
                    var edges = new List<Edge>();
                    foreach (var index in Enumerable.Range(0, desNodeitem.Nodes.Count - 1))
                    {
                        edges.Add(_edges.FirstOrDefault(x => x.StartNodeID == desNodeitem.Nodes[index] && x.EndNodeID == desNodeitem.Nodes[index + 1]));
                    }

                    edges.Add(_edges.FirstOrDefault(x => x.StartNodeID == desNodeitem.Nodes.Last() && x.EndNodeID == endPointID));
                    return new Route()
                    {
                        Edges = edges
                    };
                }

                return null;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.ToString());
                _logger.LogInformation($"startPoint:{startPointID}-endpoint:{endPointID} route faild.");
                throw;
            }
            finally
            {
                _nodeItems.ForEach(x =>
                {
                    x.Used = false;
                    x.Nodes.Clear();
                });

                IsRouting = false;
            }
        }

        private NodeItem GetUnUsedAndMinNodeItem()
        {
            return _nodeItems.Where(x => !x.Used && x.Weight != double.MaxValue).OrderBy(x => x.Weight).FirstOrDefault();
        }

        private double[] GetRowArray(double[,] source, int row)
        {
            double[] result = new double[source.GetLength(1)];
            foreach (var index in Enumerable.Range(0, result.Length))
            {
                result[index] = source[row, index];
            }

            return result;
        }

        public void Initialize(IEnumerable<Edge> edges, IEnumerable<Node> nodes)
        {
            _edges = edges.ToList();
            _nodes = nodes.ToList();
            _nodeItems = new List<NodeItem>();
            _graph = new double[_nodes.Count(), _nodes.Count()];
            foreach (var row in Enumerable.Range(0, _nodes.Count()))
            {
                var rowNode = _nodes[row];
                foreach (var colnum in Enumerable.Range(0, _nodes.Count()))
                {
                    if (row == colnum)
                    {
                        _graph[row, colnum] = 0;
                        continue;
                    }
                    var edge = _edges.FirstOrDefault(x =>
                            x.StartNodeID == rowNode.Id && x.EndNodeID == _nodes[colnum].Id);
                    _graph[row, colnum] = edge == null ? double.MaxValue : edge.Weight;
                }

                _nodeItems.Add(new NodeItem()
                {
                    NodeId = _nodes[row].Id,
                    Index = row,
                    Weight = double.MaxValue
                });
            }
        }

        public class NodeItem
        {
            public bool Used { get; set; }
            public List<int> Nodes { get; } = new List<int>();
            public int NodeId { get; set; }
            public int Index { get; set; }
            public double Weight { get; set; }
        }
    }

标签:Weight,c#,double,迪杰,算法,Nodes,var,nodes,public
From: https://www.cnblogs.com/qwqwQAQ/p/16638522.html

相关文章

  • 创建React项目全过程
    首先创建react项目可以先下载脚手架create-react-app(类似于vue的脚手架vue-cli)。1、打开****cmd,执行:npminstall-gcreate-react-app;全局安装。如果执行失败,可能是n......
  • css——复选框汉字不对齐
    1.复选框汉字不对齐<inputtype="checkbox"v-model="isAll"/><span>全选</span>2.input、span加上vertical-align:middle;属性input{vertical-alig......
  • Docker安装ElasticSearch和Kibana
    一、ElasticSearch安装1.1拉取elasticsearch镜像拉取最新版本elasticsearchdockerpullelasticsearch拉取指定版本elasticsearch,比如拉取7.17.5版本的elasticsearchdocke......
  • 强大的可视化利器 Chrome Trace Viewer 使用详解
    Limboy强大的可视化利器ChromeTraceViewer使用详解2020-03-21最近研究了下Chrome自带的TraceViewer,发现功能还挺强大的,用来做PerformanceProfil......
  • idea新建Maven项目,新建的module无法创建package
    idea新建Maven项目,新建的module无法创建package问题描述图解决问题方法原因:java文件并不是SourcesRoot,需设置成SourcesRoot步骤(图更详细):右键java文件——>点击Mar......
  • CLion使用clang-format插件使代码自动格式化
    MacOs版本下载clang-format#下载clang-format插件brewinstallinstallclang-format配置externaltool不同方式下载的clang-format地址会有不同,可以用以下......
  • Oracle数据库导出导入
    1.Oracle数据库导出expdp$username/$passwd@$ORACLE_SIDdirectory=DATA_PUMP_DIRschemas=$schemasdumpfile=$dumpfile.dmplogfile=$dumpfile.log#username数据库......
  • MYSQL中的COLLATE是什么?
    在mysql中执行showcreatetable<tablename>指令,可以看到一张表的建表语句,example如下:CREATETABLE`table1`(`id`bigint(20)unsignedNOTNULLAUTO_INCREMENT,......
  • 如何在docker swarm集群中部署一个service?
     如果你想知道,如何在dockerswarm集群中部署一个service,那么你需要仔细的阅读下面的文章····· 1、前提 如果想要完成本次文章的内容,你首先需要一个swarm集群......
  • linux crw-rw-rw- 开头的c 是啥意思?
    linuxcrw-rw-rw-开头的c是啥意思?_百度知道 https://zhidao.baidu.com/question/436282328.htmlC代表这个文件对应的是字符设备,所谓字符设备就是鼠标、键盘等,可以简单......