The A* search algorithm, the swiss knife of CodinGame

The A* search algorithm, the swiss knife of CodinGame

I love CodinGame. For those who does not know what it is about, I suggest you to try. This is a nice website that can make you better with algorithms. I like to play in some clash of code from time to time but the best still is the bot programming competition.

In the last event, I needed a way to determine the fastest way to go from point A to point B. I could have use my swiss knife Dijkstra's algorithm but it was taking way too long to come up with an answer. So I had to find an alternative.

A-star

Looking around, I found a new algorithm I did not know about, the A* search algorithm. It's path search algorithm way better in term of performance than the Dijkstra. The complexity is O(b^d) where b is the branching factor but in fact, it mostly depend of the heuristic function that will be choosen. In this example, I will choose the Manhattan calculation but it could be way different. The significant impact of A* compare to Dijkstra is that we always prefer nodes that are closer to our target and avoid visiting nodes that are further away. That, in turn, makes our algorithm more efficient since we’ll be heading in the correct general direction at each step. So in the best scenario, we have a complexity equal to the distance of our tile. In the worst, we will cross the whole game and endup with the same complexity as the Dijkstra.


But better than doing a full theory course, it's better to go directly on an example. Let's take the following example, where the red is the starting tile and the green is the end goal.

Aucun texte alternatif pour cette image

Everytime a new tile will need to be analyze, we will put the tile in an array?named openTiles. At initialization, our red starting tile will be place in the array.

openTiles.push(startTile);        

Every tile placed in the?openTiles?array will be marked as visited for not going over the same tile twice.

Once done the process can start, the goal is to search first for the accessible tile neighboring our starting tile.

const adjacentTiles = this.getAdjacentTiles(currentTile.x, currentTile.y);        
Aucun texte alternatif pour cette image

In the example above, we have 3 of them. For each of them, we will calculate the h, g and f score. I will explain the letter one by one.

In my example, the h (heuristic) score is simply the Manhattan distance between the tile I am actually analyzing and the end tile. If I calculate the Manhattan distance for each of the tile, the result will be this:

Aucun texte alternatif pour cette image

So in our case, our 3 tiles has the following h score.

adjacentTile.h = this.manhattan(adjacentTile, endTile);        
Aucun texte alternatif pour cette image

Now, let's calculate the g score. In my scenario, every tile has a cost of 1 but we could imagine tiles with different cost such as crossing mountain could cost 3 while a plain could cost only 1.

const gScore = currentTile.g + adjacentTile.cost;        
Aucun texte alternatif pour cette image

Finally, we can calculate the f score for each tile, which is just the sum of the h and g scores.

Aucun texte alternatif pour cette image

Then, we start over with the tile that obtained the smallest f score.

currentTile = openTiles.reduce(
  (best, current) => (best && best.f < current.f ? best : current),
  openTiles[0]
);        

And we repeat the whole process.

Aucun texte alternatif pour cette image

Again and again,

Aucun texte alternatif pour cette image

Until the next tile to analyze is our ending tile or until we running out of tile to analyze in which case there is no path to the ending tile.

if (currentTile.x === xEnd && currentTile.y === yEnd) {
    hasPath = true;
    break;
}        
Aucun texte alternatif pour cette image

And voila! We found the shortest path from our starting tile to the ending tile in a very optimized way. For getting a full version of the code, you can get a look at it on my GitHub.

Last words

I did not know about this algorithm and it has been a savior in the last competition for winning over some of my opponents. I am still far from the first league but I am getting better and better. I am actually focusing a bit more on this field of programation and I hope to reach the legend league in the next competition. And you, have you ever use this algorithm? Could you say in which scenario?

要查看或添加评论,请登录

Kevin Justal的更多文章

  • Node 22 is the new current!

    Node 22 is the new current!

    Node.js version 22 was released in April 2024.

  • NLP: Embedding Layer - Part II

    NLP: Embedding Layer - Part II

    Following my previous article, I will focus this time into a important component of Natural Language Processing (NLP):…

  • NLP: Summarization - Part I

    NLP: Summarization - Part I

    I recently did an interview where I encountered Spacy, a free open-source Python library for Natural Language…

  • Transactions with mongoose/mongodb

    Transactions with mongoose/mongodb

    Transactions, for those who might not be familiar, allow you to carry out multiple operations in isolation, with the…

  • Volta: extend the life of your project

    Volta: extend the life of your project

    How often have I launched a project only to discover that nothing works? How frequently have I navigated through a…

  • Did you say Scrum?

    Did you say Scrum?

    Agile, Agile, Agile..

  • Spline the new tool for amazing 3D effect

    Spline the new tool for amazing 3D effect

    I have a passion for creative development, particularly in the realms of WebGL, Three.js, and React-Three-Fiber.

  • The death of code golf with ChatGPT

    The death of code golf with ChatGPT

    Have you ever heard of code golf? It's a coder's game where the goal is to solve a problem with a minimum number of…

  • Circuit-Breaker, a nice pattern for microservices

    Circuit-Breaker, a nice pattern for microservices

    Patterns provide general solution, well documented and often proven to be helpful for making a piece of code robust and…

  • How to migrate a database from EC2 to DocumentDB on AWS?

    How to migrate a database from EC2 to DocumentDB on AWS?

    Recently, I got a very interesting task. In the name of high availability, I had to move a mongoDB database hosted on a…

社区洞察

其他会员也浏览了