迪傑斯特拉(Dijkstra)演算法是典型最短路徑演算法,用於計算一個節點到其他節點的最短路徑。 它的主要特點是以起始點為中心向外層層擴展(廣度優先遍歷思想),直到擴展到終點為止 貪心演算法(Greedy Algorithm) 貪心演算法,又名貪婪法,是尋找最優解問題的常用方法,這種方法模式一般將求解過程分 ...
迪傑斯特拉(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)
當我們理解了演算法原理後,我們需要明白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; }
}
}