-
Notifications
You must be signed in to change notification settings - Fork 1
/
DijkstraPathFinder.cs
206 lines (176 loc) · 6.85 KB
/
DijkstraPathFinder.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
/* Copyright (c) 2018-2024 Nuno Fachada and contributors
* Distributed under the MIT License (See accompanying file LICENSE or copy
* at http://opensource.org/licenses/MIT) */
using System;
using System.Collections.Generic;
namespace LibGameAI.PathFinding
{
/// <summary>
/// A path finder implemented with the Dijkstra algorithm. Always finds
/// the shortest path.
/// </summary>
/// <remarks>
/// Optimizations to be done (some are code-related with others):
/// TODO Use a heap/priority queue (priority heap) data structure for the
/// open and closed nodes.
/// TODO Either make NodeRecord structs (and update surrounding code
/// appropriately) or use an object pool of NodeRecords.
/// TODO Avoid always getting node record from the dictionary, just pull
/// it once onto a local variable and use that.
/// </remarks>
public class DijkstraPathFinder : IPathFinder
{
// Auxiliary collections
private List<NodeRecord> open, closed;
private IDictionary<int, NodeRecord> nodeRecords;
private Stack<IConnection> path;
// This private class is used to keep node records for the shortest
// path algorithm.
private class NodeRecord : IComparable<NodeRecord>
{
public int Node { get; }
public IConnection Connection { get; set; }
public float CostSoFar { get; set; }
public NodeRecord(int node)
{
Node = node;
Connection = null;
CostSoFar = 0.0f;
}
public int CompareTo(NodeRecord other)
{
return Math.Sign(CostSoFar - other.CostSoFar);
}
}
/// <summary>
/// Create a new Dijkstra shortest path finder.
/// </summary>
public DijkstraPathFinder()
{
open = new List<NodeRecord>();
closed = new List<NodeRecord>();
nodeRecords = new Dictionary<int, NodeRecord>();
path = new Stack<IConnection>();
}
public IEnumerable<int> OpenNodes
{
get
{
foreach (NodeRecord nr in open)
{
yield return nr.Node;
}
}
}
public IEnumerable<int> ClosedNodes
{
get
{
foreach (NodeRecord nr in closed)
{
yield return nr.Node;
}
}
}
/// <summary>
/// Find shortest path between start and goal nodes.
/// </summary>
/// <param name="graph">Graph where to perform search.</param>
/// <param name="start">Start node.</param>
/// <param name="goal">Goal node.</param>
/// <returns>
/// An enumerable containing the connections that constitute
/// the shortest path from start to goal.
/// </returns>
public IEnumerable<IConnection> FindPath(
IGraph graph, int start, int goal)
{
// Current node
int current;
// Clear collections
open.Clear();
closed.Clear();
nodeRecords.Clear();
// Initialize the record for the start node
nodeRecords[start] = new NodeRecord(start);
// "Current" node is start node
current = start;
// Initialize the open list by adding the starting node
open.Add(nodeRecords[start]);
// Iterate through processing each node
while (open.Count > 0)
{
// Find element with smallest cost so far in the open list
open.Sort();
current = open[0].Node;
// If it is end node, break out of node processing loop
if (current == goal) break;
// Otherwise get the node outgoing connections
foreach (IConnection conn in graph.GetConnections(current))
{
// Index of node record in the open and closed lists
int nrIndex;
// The node record itself
NodeRecord nodeRec;
// Function to find specific node in a list
Predicate<NodeRecord> findNodePred =
nr => nr.Node == conn.ToNode;
// Get cost estimate for the "to node"
float toNodeCost =
nodeRecords[current].CostSoFar + conn.Cost;
// Skip if the node is closed
nrIndex = closed.FindIndex(findNodePred);
if (nrIndex >= 0) continue;
// If node is open...
nrIndex = open.FindIndex(findNodePred);
if (nrIndex >= 0)
{
// ...and we find a worse route, also skip
if (open[nrIndex].CostSoFar <= toNodeCost) continue;
// Otherwise, keep node record
nodeRec = open[nrIndex];
}
else
{
// If we're here we've got an unvisited node, so make
// a record for it
nodeRec = new NodeRecord(conn.ToNode);
nodeRecords[conn.ToNode] = nodeRec;
// And add it to the open list
open.Add(nodeRec);
}
// We're here if we need to update the node
// Update the cost and connection
nodeRec.CostSoFar = toNodeCost;
nodeRec.Connection = conn;
}
// We've finished looking at the connections for the current
// node, so add it to the closed list and remove it from the
// open list
open.Remove(nodeRecords[current]);
closed.Add(nodeRecords[current]);
}
// We're here if we've either found the goal, or if we've no more
// nodes to search
if (current != goal)
{
// We've run out of nodes without finding the goal, so there's
// no solution
return null;
}
else
{
// Compile the list of connections in the path
path.Clear();
// Work back along the path, accumulating connections
while (current != start)
{
path.Push(nodeRecords[current].Connection);
current = nodeRecords[current].Connection.FromNode;
}
// Return the path
return path;
}
}
}
}