CodexBloom - Programming Q&A Platform

Issue with Implementing the A* Pathfinding Algorithm in C# - Heuristic Not Leading to Optimal Path

πŸ‘€ Views: 70 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-04
c# algorithm pathfinding a-star C#

I just started working with I'm reviewing some code and I'm not sure how to approach I'm building a feature where I've searched everywhere and can't find a clear answer... I'm currently trying to implement the A* pathfinding algorithm in C#, but I'm encountering an issue where the algorithm does not consistently return the optimal path. I have a grid-based map where some cells are walkable and others are obstacles. The heuristic I'm using is the Manhattan distance, but the paths returned often seem longer than expected. Here’s a snippet of my implementation: ```csharp public class Node { public int X { get; set; } public int Y { get; set; } public int GCost { get; set; } public int HCost { get; set; } public int FCost => GCost + HCost; public Node Parent { get; set; } } public List<Node> AStar(Node start, Node goal, List<Node> walkableNodes) { var openSet = new List<Node> { start }; var closedSet = new HashSet<Node>(); while (openSet.Count > 0) { Node currentNode = openSet.OrderBy(node => node.FCost).First(); if (currentNode == goal) { return RetracePath(start, currentNode); } openSet.Remove(currentNode); closedSet.Add(currentNode); foreach (var neighbor in GetNeighbors(currentNode, walkableNodes)) { if (closedSet.Contains(neighbor)) continue; int newCostToNeighbor = currentNode.GCost + GetDistance(currentNode, neighbor); if (newCostToNeighbor < neighbor.GCost || !openSet.Contains(neighbor)) { neighbor.GCost = newCostToNeighbor; neighbor.HCost = GetHeuristic(neighbor, goal); neighbor.Parent = currentNode; if (!openSet.Contains(neighbor)) { openSet.Add(neighbor); } } } } return new List<Node>(); // Return an empty path if no path found } ``` When I run the algorithm, it sometimes takes me through longer routes, especially when there are multiple paths available. I have debugged the values for GCost and HCost, and they seem to be calculated correctly. However, the final path does not align with what I expect based on the heuristic. I have also tried adjusting the heuristic to use Euclidean distance instead of Manhattan distance, but the results are still similar. I’m using C# 9.0 and .NET 5.0 for this implementation. Is there a common mistake or an overlooked detail that could lead to suboptimal pathfinding in the A* algorithm? Any suggestions would be greatly appreciated! For context: I'm using C# on Windows. What's the best practice here? What's the best practice here? I recently upgraded to C# 3.10. I'd be grateful for any help.