A * brief introduction to Algorithms

Source: Internet
Author: User

A * search algorithm, also known as the astar algorithm, is one of the heuristic search algorithms. It is a path with multiple nodes on the graphic plane to find the lowest cost. It is often used in the mobile computing of the NPC in the game or the mobile computing of the BOT in the online game. Like Dijkstra, this algorithm can find a shortest path and perform heuristic search like BFs.

A * the most important part of an algorithm lies in the design of a valuation function:
F (n) = g (n) + H (N)

F (n) is the valuation of every possible test point. It consists of two parts:
In part, g (n) indicates the cost from the start point to the current point (usually expressed by the depth of a node in the Search Tree ).
Another part is H (n), which indicates the most important part in Heuristic Search, that is, the valuation from the current node to the target node,
The Design of H (n) directly affects whether a * algorithm is a heuristic algorithm with such heuristic functions.

A Heuristic Algorithm with a f (n) = g (n) + H (n) strategy can be a sufficient condition for a * algorithm:
1. There is an optimal path from the start point to the end point on the search tree.
2. The problem domain is limited.
3. The search value for all nodes is greater than 0.
4. H (n) = <H * (N) (H * (N) is the substitute value of the actual problem ).

When all four conditions are met, a heuristic algorithm with F (n) = g (n) + H (n) strategy can become a * algorithm, and the optimal solution can be found.

For a search question, it is clear that conditions 1, 2, and 3 are easily met, while conditions 4: H (n) <= H * (N) need to be carefully designed, H * (N) is obviously unknown, so h (N), an inspiration strategy that meets Condition 4, is very valuable.

However, for the Optimal Path search and Digital 8 problems of graphs, some related strategies H (n) are not only well understood, but also theoretically proved to meet Condition 4, this plays a decisive role in promoting this algorithm.

H (n) Distance from H * (N) cannot be too large. Otherwise, H (n) will not have a strong differentiation capability, and the algorithm efficiency will not be very high. A good evaluation of H (n) is that h (n) is under the lower bound of H * (N) and is as close as possible to H * (N ).

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

This blog was published by Johann fradj, a member of the IOS tutorial team. He is currently a full-time senior iOS development engineer. He is the founder of Hot apps factory and developed app cooker.

 

Learn how the astar pathfinding algorithm works!

Do you want to create monsters or game protagonists when you are playing a game, so that they can be moved to a specific position to avoid walls and obstacles?

If so, please refer to this tutorial and we will show you how to use the astar pathfinding algorithm to implement it!

There are already a lot of articles on the astar pathfinding algorithm on the Internet, but most of them are provided to senior developers who already know the basic principles.

This tutorial will start with the basic principles. We will explain the axing pathfinding algorithm step by step. The examples are provided with many illustrations and examples.

No matter what programming language or operating platform you are using, you will find this tutorial helpful because it explains the principles of algorithms at the non-programming language level. A later tutorial will show you how to implement the astar Algorithm in cocos2d iPhone games.

Find the shortest path for reaching a cup of caffeine and delicious snacks! :]

 

A Pathfinder

 

Let's imagine that there is a game where a cat wants to find a way to get the bones.

"Why does a cat want bones ?!" You may think so. In this game, this is a sly cat. He wants to pick up the bones and give them to the dog to prevent being killed! :]

Now imagine that the cat in the figure wants to find the shortest path to the bone:

Unfortunately, a cat cannot go straight from its current position to its bone position, because a wall blocks the path and it is not a ghost cat in the game!

The cat in the game is also lazy and always wants to find the shortest path, so that it will not be too tired when he comes home to visit his girlfriend :-)

But how do we compile an algorithm to calculate the path that the cat wants to select? The astar algorithm has saved us!

 

Simplified search area

 

The first step is to simplify the search area to be easily controlled.

It depends on the game. For example, we can divide the search area into pixels, but this division granularity is too high for our box-based game (not necessary ).

Instead, we use squares (a square) as the unit of the pathfinding algorithm. Other shape types are also possible (such as triangles or hexagonal), but squares are the simplest and most suitable for our needs.

Like that, our search area can be simply represented by a two-dimensional array of map size. Therefore, if it is a 25*25-square map, our search area will be an array with 625 square characters. If we divide the map into pixels, the search area is an array with 640,000 square characters (a square is 32*32 pixels )!

Now let's divide the region into multiple squares to represent the search space based on the current region (in this simple example, 7*6 squares = 42 squares ):

 

Open and closed lists

 

Now that we have created a simple search area, let's discuss how the astar algorithm works.

Apart from laziness, our cat does not have good memory, so it requires two lists:

  1. A record of all squares (called the open list) that are considered to find the shortest path)
  2. A block that will not be considered under a record (as a closed list)

The cat first adds the current location to the closed list (we call this start point ""). Then, add all the accessible blocks adjacent to the current location to the open list.

Is the scene of a cat at a certain position (green represents the open list ):

Now, the cat needs to determine which of these options is the shortest path, But how should it choose?

In the axing pathfinding algorithm, a value is called a path increment by giving each square a value. Let's take a look at how it works!

Path Increment

 

We will give each square a G + H and A value:

  • G indicates the movement from the start point A to the current square. Therefore, the movement from the starting point A to the adjacent small square is 1, and the value increases as the starting point leaves.
  • H is from the current square to the target point (we call it point B, representing the bone !) The estimated value of the movement. This is often called a visit because we are not sure what the volume of movement is-just an estimate.

You may be interested in "Mobile volume. In the game, this concept is simple-just the number of squares.

However, you can adjust this value in the game. For example:

  • If you allow diagonal lines to move, you can increase the volume of movement for diagonal lines.
  • If you have different terrain, you can increase the volume of movement, for example, targeting a swamp, water, or catgirl poster :-)

This is the general meaning-Now let's analyze in detail how to calculate the G and H values.

G value

 

G is the volume of movement from the start point A to the current square (in this game, it refers to the number of squares ).

To calculate the value of G, we need to obtain it from its forward step (the previous square), and then add 1. Therefore, the G value of each square represents the total movement from point A to the path formed by the square.

For example, two paths to different bones are displayed. Each square is marked with its G value:

H value

The H value is an estimate of the movement from the current square to the end (in this game, it refers to the number of squares ).

The closer the mobile estimation value is to the actual value, the more precise the final path. If the estimation value stops, it is likely that the generated path will not be the shortest (but it may be close ). This topic is relatively complex, so we will not explain it in this tutorial, But I provide a network link at the end of the tutorial, which is a good explanation.

To make it simpler, we will use the "Manhattan distance method" (also called "Manhattan long" or "city block distance"). It just calculates the distance point B, the remaining number of horizontal and vertical blocks skips the number of obstacles or different land types.

For example, it shows how to use "city block distance" to estimate the value of H from different start points to end points (black ):

Astar Algorithm

 

Now that you know how to calculate the sum of each square (we call it f, equal to G + H), let's look at the principles of the astar algorithm.

The cat will repeat the following steps to find the shortest path:

  1. Add the square to the open list. The list has the smallest value. And call this square S.
  2. Remove s from the open list and add s to the closed list.
  3. For each block adjacent to s that can pass through T:
    1. If t is in the closed list: Ignore it.
    2. If t is not in the open list: add it and calculate its value.
    3. If t is already in the open list: When we use the current generated path to get there, check whether the F and value are smaller. If yes, update its value and its predecessors.

If you still have some questions about how it works, don't worry-we will introduce it step by step with examples! :]

Cat path

Let's take a look at our example of the slow Cat's journey to the bone.

In, I listed each value in formula F = G + H based on the following:

  • F (sum of squares): upper left corner
  • G (movement from point A to square): lower left corner
  • H (estimated movement from square to B): bottom right corner

At the same time, the arrow shows the direction to move to the corresponding square.

Finally, in each step, the Red Square indicates the closed list, and the green square indicates the open list.

Okay. Let's get started!

Step 1

In the first step, the cat will determine the adjacent squares relative to the start position (point a), calculate their F and value, and then add them to the open list:

The H value is listed in each square (two values are 6 and one is 4 ). I suggest you calculate the values of Blocks Based on "city block distance" to ensure that you understand its principles.

Note that the F value (in the upper left corner) is the sum of the G value (in the lower left corner) and H value (in the lower right corner.
Step 2

In step 2, the cat selects the square with the smallest F and value, adds it to the closed list, and then retrieves the relevant values of its adjacent squares.

Now you will see the square with a minimum increment of 4. The cat tries to add all adjacent squares to the open list (and then calculate their values), except the cat's own squares cannot be added (because it has been added to the closed list) or it is a wall block (because it is not accessible ).

Note that the G value of the two new blocks added to the open list is increased by 1 because they are far away from the start point and there are two blocks. You may need to calculate the "city block distance" to ensure that you understand the H value of each new square.
Step 3

Again, we select the square with the minimum F and value (5) and continue to repeat the previous steps:

Now, only one possible square is added to the open list, because there is already an adjacent square in the close list, and the other two are wall blocks.

Step 4

Now we have an interesting situation. As you can see before, the F and value of the four squares are all 7-What should we do ?!

There are several solutions available, but the simplest (FAST) method is to keep following the squares recently added to the open list. Now proceed along the recently added square.

This time there are two adjacent squares that can pass through. We still calculate their values as before.
Step 5

Then we select the square with the minimum value (7) and repeat the previous steps:

We are getting closer and closer to the end!

Step 6

You are well trained now! I bet you can guess the next step is like this:

We are almost at the end, but this time you will see two shortest paths to reach the bone for us to choose:

In our example, there are two shortest paths:

  • 1-2-3-4-5-6
  • 1-2-3-4-5-7

It doesn' t really matter which of these we choose, it comes down to the actual implementation in code.

It doesn't matter which one to choose. Now it's time to implement it with code.

Step 7

Let's repeat the steps from one block:

Aha, the bones are in the open list!
Step 8

Now that the target square is in the open list, the algorithm will add it to the closed list:

Then, all the algorithm has to do is return and calculate the final path!

A foresight cat

In the above example, we can see that when a cat is looking for a shortest path, it often chooses a better square (the square on its future Shortest Path) -It seems like it is a far-sighted cat!

But if a cat is blind and always chooses the first square to be added to its list, what will happen?

Shows all the squares that will be used during the search process. You will see that the cat is trying more squares, but it still finds the shortest path (not the previous one, but another equivalent ):

The red squares in the figure do not represent the shortest path. They only represent the squares selected as "S" at a certain time.

I suggest you look at the figure above and try the steps again. No matter which adjacent square you see this time, choose the "worst" approach. You will find the shortest path!

So you can see that there is no problem with following a "wrong" square, and you will still find the shortest path after repeated attempts.

Therefore, in our implementation, we will add squares to the open list according to the following algorithms:

  • The adjacent squares return these order: ToP/left/bottom/Right.
  • When all squares have the same value, the squares are added to the open list (so the first square to be added is selected by the first cat ).

The following is returned from the original path:

The shortest path consists of step-by-step return from the end point to the start point (for example, we can see the arrow pointing to the right at the end point, so the forward direction of the square is on its left ).

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.