45 lines
1.5 KiB
C#
45 lines
1.5 KiB
C#
namespace AdventOfCode.Core.Shared.A_Star
|
|
{
|
|
public class AStarGrid(AStarNode[] data) : Grid<AStarNode>(data)
|
|
{
|
|
public int TileMoveCost { get; set; }
|
|
|
|
public int MinimalSteps(AStarNode start, AStarNode destination)
|
|
{
|
|
List<AStarNode> openNodes = [start];
|
|
List<AStarNode> closedNodes = [];
|
|
|
|
while(openNodes.Count != 0)
|
|
{
|
|
// get the lowest F-cost node
|
|
AStarNode current = openNodes.OrderBy(n => n.FCost).First();
|
|
openNodes.Remove(current);
|
|
current.CloseNode();
|
|
closedNodes.Add(current);
|
|
|
|
if (current == destination)
|
|
{
|
|
//done
|
|
return 1;
|
|
}
|
|
|
|
var neighbors = GetNeighbors(current, false);
|
|
neighbors = neighbors.Where(n => current.CanMoveTo(current));
|
|
|
|
// calc costs
|
|
foreach(AStarNode neighbor in neighbors)
|
|
{
|
|
neighbor.ParentNode = current;
|
|
// since we only move straight the move cost is always the same
|
|
neighbor.GCost = current.GCost + TileMoveCost;
|
|
neighbor.HCost = neighbor.GetManhattanDistance(destination) * TileMoveCost;
|
|
neighbor.OpenNode();
|
|
openNodes.Add(neighbor);
|
|
}
|
|
}
|
|
|
|
return -1;
|
|
}
|
|
}
|
|
}
|