15,843,727 members
Articles / Web Development / HTML

# Pathfinding Algorithms in C#

Rate me:
3 Apr 2023CPOL4 min read 237.1K   9.7K   228   77
A comparison of Dijkstra and Astar

Unzip and open solution in Visual Studio 2022

## Introduction

Have you ever wondered how GPS applications calculate the fastest way to a chosen destination? As you will see, it is actually quite simple.

This article explains this and provides sample code that you are free to use as you like. The article also compares two common basic algorithms, Dijkstra and A*.

## The Problem

Let’s say you have a map. You know where you are and where you want to go. The map has roads (they are called edges) that connect the nodes (places with coordinates).

From every node, you can go to one or many edges. An edge has a cost (e.g. length or time it takes to travel it).
For small maps, one could perhaps calculate all possible routes to the destination and select the shortest. But that is not very practical for maps with many nodes as the combinations grow exponentially.

## Dijkstra

The Dijkstra algorithm was discovered in 1959 by Edsger Dijkstra. This is how it works:

1. From the start node, add all connected nodes to a priority queue.
2. Sort the priority queue by lowest cost and make the first node the current node.
For every child node, select the best that leads to the shortest path to start.
When all edges have been investigated from a node, that node is "`Visited`" and you don´t need to go there again.
3. Add each child node connected to the current node to the priority queue.
4. Go to step 2 until the queue is empty.
5. Recursively create a list of each nodes node that leads the shortest path from end to start.
6. Reverse the list and you have found the shortest path

In other words, recursively for every child of a node, measure its distance to the start. Store the distance and what node led to the shortest path to start. When you reach the end node, recursively go back to the start the shortest way, reverse that list and you have the shortest path.

Below is my Dijkstra Algorithm implementation in C# code. It might be easier to understand than the above.

C#
```public List<Node> GetShortestPathDijkstra()
{
DijkstraSearch();
var shortestPath = new List<Node>();
BuildShortestPath(shortestPath, End);
shortestPath.Reverse();
return shortestPath;
}

private void BuildShortestPath(List<Node> list, Node node)
{
if (node.NearestToStart == null)
return;
BuildShortestPath(list, node.NearestToStart);
}

private void DijkstraSearch()
{
Start.MinCostToStart = 0;
var prioQueue = new List<Node>();
do {
prioQueue = prioQueue.OrderBy(x => x.MinCostToStart).ToList();
var node = prioQueue.First();
prioQueue.Remove(node);
foreach (var cnn in node.Connections.OrderBy(x => x.Cost))
{
var childNode = cnn.ConnectedNode;
if (childNode.Visited)
continue;
if (childNode.MinCostToStart == null ||
node.MinCostToStart + cnn.Cost < childNode.MinCostToStart)
{
childNode.MinCostToStart = node.MinCostToStart + cnn.Cost;
childNode.NearestToStart = node;
if (!prioQueue.Contains(childNode))
}
}
node.Visited = true;
if (node == End)
return;
} while (prioQueue.Any());
}```

This is a randomly generated map in my test program. The dots are nodes and between them are lines which represent edges. This map consists of 5000 nodes and 15000 edges.

Lighter colored dots are visited by the search algorithm and the best path is drawn in green.

## A* Algorithm

There are many improvements of Dijkstra’s algorithm. One of the most common is called A*. It is basically the same as Dijkstra with one simple modification.

Edges are prioritized also with respect to how much closer that edge leads to a straight-line distance to the goal. So before running an A* search, the straight-line distance to the final destination has to be measured for every node, which is easy if you know each nodes coordinate. This is the simplest form of A* and its definition also allows for improvments of the heuristics function. (In this case StraightLineDistanceToEnd)

This algorithm has a big performance advantage since it does not need to visit as many nodes when the direction of the path end is known.

See my implementation below. In bold what is added to Dijkstra’s Algorithm.

C#
```public List<Node> GetShortestPathAstar()
{
foreach (var node in Map.Nodes)
node.StraightLineDistanceToEnd = node.StraightLineDistanceTo(End);
AstarSearch();
var shortestPath = new List<Node>();
BuildShortestPath(shortestPath, End);
shortestPath.Reverse();
return shortestPath;
}

private void AstarSearch()
{
Start.MinCostToStart = 0;
var prioQueue = new List<Node>();
do {
prioQueue = prioQueue.OrderBy(x => x.MinCostToStart + x.StraightLineDistanceToEnd).ToList();
var node = prioQueue.First();
prioQueue.Remove(node);
NodeVisits++;
foreach (var cnn in node.Connections.OrderBy(x => x.Cost))
{
var childNode = cnn.ConnectedNode;
if (childNode.Visited)
continue;
if (childNode.MinCostToStart == null ||
node.MinCostToStart + cnn.Cost < childNode.MinCostToStart)
{
childNode.MinCostToStart = node.MinCostToStart + cnn.Cost;
childNode.NearestToStart = node;
if (!prioQueue.Contains(childNode))
}
}
node.Visited = true;
if (node == End)
return;
} while (prioQueue.Any());
}```

This is the same map as above, but the path is calculated with A* algorithm. As you can see, there are much less nodes that needs to be visited.

## Results

When running both algorithms on the same map of 500,000 nodes, I get these results.

 Dijkstra A* Visited nodes 330,871 19,410 Time to calculate (ms) 850 127 Cost of best path 14.3 14.3 Distance of shortest path 0.824 0.824

As you can see in the table above, A* algorithm is about 7 times faster than Dijkstra, and they both find the shortest path and same lowest cost. In any case the A* algorith should be the best choice.

On a real map, the shortest path isn’t always the best. Driving on roads with higher speed limit will probably take you to your destination sooner. That is why adding a random number to the cost of an edge makes this experiment more realistic.

The larger the map is compared to how many nodes lay between start and finish the more the Time to calculate shortest path will decrease using A*.

## Conclusion

So what algorithm is the best path finding algorithm of Dijkstra and A*?
I’d say it is A*. It will always give a faster search, and it gives the same result as Dijkstra.

Thanks for reading and I hope you find path finding algorithms are as much fun as I do by now.

Have a nice day!

## History

• December 10, 2017 - Version 1.0
• December 20, 2017 - Version 1.0.1
• Minor spelling fixes
• Januari 13, 2018 - Version 1.0.2
• Clarified that A* can be improved.
• April 3, 2023 - Version 1.1
• Changed my conclusion. Thanks readers.

Written By
Software Developer (Senior)
Sweden
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

 First PrevNext
 My vote of 5 LussoTorino16-Aug-23 3:20 LussoTorino 16-Aug-23 3:20
 My vote of 5 Member 195950113-Apr-23 14:09 Member 1959501 13-Apr-23 14:09
 Serendipity! honey the codewitch5-Apr-23 2:00 honey the codewitch 5-Apr-23 2:00
 Re: Serendipity! KristianEkman7-Apr-23 0:04 KristianEkman 7-Apr-23 0:04
 node.ConnectClosestNodes() does not set cost of backconnection Member 1570729514-Jul-22 23:49 Member 15707295 14-Jul-22 23:49
 Re: node.ConnectClosestNodes() does not set cost of backconnection jfregnault2-Apr-23 0:38 jfregnault 2-Apr-23 0:38
 Re: node.ConnectClosestNodes() does not set cost of backconnection KristianEkman2-Apr-23 4:27 KristianEkman 2-Apr-23 4:27
 specify start and end nodes manully mohammedX618-Jun-22 1:39 mohammedX6 18-Jun-22 1:39
 Re: specify start and end nodes manully KristianEkman19-Jun-22 5:39 KristianEkman 19-Jun-22 5:39
 Much less nodes??????????????? Geno Carman8-Sep-21 5:34 Geno Carman 8-Sep-21 5:34
 Re: Much less nodes??????????????? KristianEkman9-Sep-21 11:36 KristianEkman 9-Sep-21 11:36
 Re: Much less nodes??????????????? Geno Carman10-Sep-21 5:59 Geno Carman 10-Sep-21 5:59
 Path chosen does not look optimal Matty R7-Sep-21 20:47 Matty R 7-Sep-21 20:47
 Re: Path chosen does not look optimal KristianEkman9-Sep-21 11:32 KristianEkman 9-Sep-21 11:32
 Re: Path chosen does not look optimal Daniele Rota Nodari11-Apr-23 0:19 Daniele Rota Nodari 11-Apr-23 0:19
 Re: Path chosen does not look optimal Alberto Armando4-Apr-23 4:41 Alberto Armando 4-Apr-23 4:41
 My vote of 5 DrABELL5-Sep-21 10:50 DrABELL 5-Sep-21 10:50
 Re: My vote of 5 KristianEkman5-Sep-21 21:06 KristianEkman 5-Sep-21 21:06
 distance jevdsnny215-Dec-18 16:19 jevdsnny2 15-Dec-18 16:19
 Re: distance Dmitriy Gakh15-Dec-18 18:00 Dmitriy Gakh 15-Dec-18 18:00
 Re: distance jevdsnny216-Dec-18 1:55 jevdsnny2 16-Dec-18 1:55
 Thanks kieslowski_tr126-Dec-18 1:37 kieslowski_tr12 6-Dec-18 1:37
 kavyarathi Member 1407022628-Nov-18 2:08 Member 14070226 28-Nov-18 2:08
 Articles Explorer Whiz8-Jul-18 19:48 Explorer Whiz 8-Jul-18 19:48
 Rapidly-exploring random trees? ipavlu1-Jul-18 15:19 ipavlu 1-Jul-18 15:19
 Last Visit: 31-Dec-99 19:00     Last Update: 21-Feb-24 9:18 Refresh 1234 Next ᐅ