8 digital's 8 realm

Source: Internet
Author: User

 

8 digital's 8 realm


It is difficult to study the classic questions. We will come up with a practical question for deduction. Eight Digital problems have a corresponding question in the Peking University online evaluation system. The question is described as follows:

Eight

Time Limit: 1000 MS Memory Limit: 65536 K Special Judge

Description

The 15-puzzle has been aroundfor over 100 years; even if you don't know it by that name, you 've got it. itis constructed with 15 sliding tiles, each with a number from 1 to 15 on it, and all packed into a 4 by 4 frame with one tile missing. let's call themissing tile 'X'; the object of the puzzle is to arrange the tiles so that theyare ordered:

1 2 3 4

5 6 7 8

9 10 1112

13 14 15 x

Where the only legal operationis to exchange 'X' with one of the tiles with which it shares an edge. As anexample, the following sequence of moves solves a slightly scrambled puzzle:

1 2 3 4 1 2 4 1 2 3 4 4 4

5 6 7 8 5 6 7 8 5 6 6 7 8 5 6 7 8

9x1012 9 10x12 9 10 11 12 9 10 11 12

13 14 11 15 13 14 11 15 13 14x15 14

R-> d-> r->

The letters in the previusrow indicate which neighbor of the 'X' tile is swapped with the 'X' tile ateach step; legal values are 'R', 'l ', 'U' and 'D', for right, left, up, and down, respectively.

Not all puzzles can be solved; in 1870, a man named Sam Loyd was famous for distributing an unsolvable versionof the puzzle, and

Frustrating extends people. Infact, all you have to do to make a regular puzzle into an unsolvable one is toswap two tiles (not counting the missing 'X' tile, of course ).

In this problem, you willwrite a program for solving the less well-known 8-puzzle, composed of tiles ona three by three arrangement.

Input

You will receive a descriptionof a configuration of the 8 puzzle. the description is just a list of the tilesin their initial positions, with the rows listed from top to bottom, and thetiles listed from left to right within a row, where the tiles are representedby numbers 1 to 8, plus 'x '. for example, this puzzle

1 2 3

X 4 6

7 5 8

Is described by this list:

1 2 3x4 6 7 5 8

Output

You will print to standardoutput either the word ''unsolvable'', if the puzzle has no solution, or astring consisting entirely of the letters 'R', 'l ', 'U' and 'D' that describesa series of moves that produce a solution. the string shoshould include no spacesand start at the beginning of the line.

Sample Input

2 3 4 1 5x7 6 8

Sample Output

Ullddrurdllurdruldr

 

This topic is SpecialJudge. You can find a group of shift methods at will, but in many cases, we need to find the shift method with the least number of steps. Therefore, here we aim at the shift method with the least number of steps. Real optimization involves many issues, such as A *, full sorting hash, and heap optimization. One realm and one code, let's go through one realm and one realm, and gradually optimize this classic problem. Of course, I am not so bored and will not list all realms of code ......

 

Realm 1: Brute Force Search + STL

At the beginning, we naturally considered using the most intuitive and extensive search, because the state cannot exceed 0.4 million at most, and the computer is still acceptable, because the extensive search needs to record the status and need to determine the weight, therefore, you can convert the status of each graph to a string, store it in the stl Container set, and use the special functions of set to determine the weight. Because the internal implementation of set is a red/black tree, the complexity of each insert or query is Log (n). Therefore, if the entire algorithm traverses all states, the complexity required is n * Log (n), which is about 1 million, it can be accepted by the computer. Because the string operation is time-consuming and the stl is comprehensive, the speed is not fast enough, so the calculation is time-consuming. Such code can only solve any problem within 10 seconds. However, the efficiency is obviously not high enough. The requirement on POJ is 1 second and cannot be passed. For the first code, see Code1.cpp.

 

Realm 2: Search + hash

Considering that time-consuming mainly lies in STL, for large-scale traversal, the use of ST's set and string causes a great loss in efficiency. Therefore, it is now facing a serious problem, you must judge it by yourself. For efficiency, you must make your own hash. A little troublesome. the hash function is actually 9! And each sort corresponds to a number. Search online to learn the correspondence between the arrangement and numbers. N! It is the base, and the reverse order value of the nth digit of the State is the nth digit of the hash value. For spaces, take 9 and multiply it by 8 !. For example, the hash value of 1 3 7 24 6 9 5 8 is 0*0! + 2*1! + 0*2! + 1*3! + 3*4! + 1*5! + 0*6! + 1*7! + 0*8! <9! For specific reasons, you can check out some mathematical books. Among them, the hash value of 1 2 34 5 6 7 8 9 is the minimum value of 0, and the hash value of 9 8 7 6 54 3 2 1 is (9! -1) maximum. The other values are from 0 to (9! -1), and all are unique. After removing all STL and even String, We can get code for one-way wide search + Hash. The algorithm can solve the problem in three seconds, but it is not fast enough! The time limit for POJ is 1 second. After a simple change, the path record method is changed from a string to a single character, and the parent node is recorded, 266ms is the upper limit for solving a single problem. Of course, there is also a small modification technique, that is, the reverse logarithm will not change. Through this, you can directly determine whether an input has a feasible solution. This optimization does not work for input in the worst case of a single group, so it does not reduce the time limit for input in a single group. For the code optimized, see Code2.cpp.

 

Realm 3: wide search + hash + Table Creation

Yes, the problem can be solved within-ms. However, we note that in the worst case, all reachable states may be searched and cannot be found. If this question is entered multiple times, a large amount of computing is required each time. In fact, here we can consider from the opposite direction, from the final needs of the status, such as the situation required by POJ 1077, the situation is fixed. You can use the Hash method mentioned above to find all the values corresponding to the reachable state, and use a bool table to record the values in the reachable state, use the similar method of "Realm 3" to record the path and input it into the table. Then, after a table is typed, the result is directly called after each input! In this way, regardless of the number of input conditions, the result is successful once, and the result will be obtained in the O (1) time later! In this way, multiple group inputs of ZOJ are fatal! The code of this realm is not changed much and will not be given any more, the same below.

 

  Realm 4. Bidirectional wide search + hash
Hash, I will not go into details. Now, we will further optimize it. In order to reduce the expansion of the State, we naturally think of two-way wide search, the search starts from the input status point and the target status 1 2 3 4 5 6 7 8 9 at the same time. When a status is searched in another direction, the search is successful and the two directions are connected, the final result is displayed. If the traversal in one direction is complete and the other direction is still not met, the result cannot be completed and the code is no longer provided. For the reason, see ......

 

  Realm 5. A * + hash + simple valuation function
When extensive search is used, you can think of using the classic A * solution and using depth as g (n). The rest is naturally an inspiration function. For Digital 8, the heuristic function can use two states with different numbers. The next step is A *'s routine. The specific idea of A * will not be repeated, because the AI textbook must be clearer than I did. However, you must note that A * must meet two conditions:

1. h (n)> h '(n), h' (n) is the actual optimal generation value from the current node to the target point.

2. The F value of each extended node is smaller than or equal to the F value of the parent node.

Naturally, we have to verify our heuristic function. h verification is simple, not to mention, because g is the depth, each time it will increase by 1 compared with the parent node. Let's look at h again. In terms of understanding, we only need to regard h as the real "Eight Digital" and empty spaces. Here, we will find that each movement can result in a regression of at most one number, or a subtraction of not-in-place digits. H can be reduced by 1 at most, while g thinks it is the depth, which increases by 1 at a time. Therefore, f = g + h is naturally not decreasing. In this way, A * can be used to meet the two conditions of! The code of this realm is not listed, because the last few codes that have been optimized are the parent set or upgraded version of this realm. Since the logic is the same, we only give the highest level.

Realm 6, A * + hash + Manhattan distance

The core of A * is the function of inspiration. If realm 5 is to be upgraded, the function of inspiration is first thought. Here, the Manhattan distance can be used as our inspiration function. The distance from Manhattan sounds mysterious, but it is actually "the total absolute axis distance". It uses eight digital devices, which is equivalent to the minimum number of moves required to reset all numbers. As an inspiration function, we naturally need to meet the two conditions mentioned in realm 5. Now we can see that the distance from this Manhattan is naturally met. For the second one, because space is stripped out by us, We only care about the number to be exchanged when switching. It goes forward to 1 for the multi-direction target, and the depth is increased by 1 every time as g, in this way, g + h is at least equal to the original, so the second condition is also met. A * is available and has A more optimized heuristic function. Because it can be upgraded, so ...... The code is not given.

 

Realm 7, A * + hash + Manhattan distance + small top heap

After the above optimization, we found that A * also has some advantages, because each time we need to find the smallest element of f in the so-called Open table, if each order, so the sorting workload can be said to be very large, even if it is fast, the program is not fast enough! Here, we can think of the need to dynamically add elements to dynamically obtain the minimum value of the program, we can maintain a small top heap, the effect is. Each time the minimum element is obtained, instead of using an n * Log (n) sort, it is good to use log (n) to find and adjust the heap, the algorithm has taken another big step forward. Here, we finally want to provide the Code. For the code, see Code3.Cpp.

 

Realm 8, IDA * + Manhattan distance

IDA * is the * search with iterative deepening. The Code is the most concise and requires no heavy status judgment and no sort of valuation. In this case, the hash table is not used, and it does not need to be applied on the heap. The space requirement is reduced. In terms of efficiency, the Manhattan distance is applied. At the same time, when finding the optimal solution based on the depth and h value, we can perform pruning on the areas beyond the current optimal solution, which can lead to a sharp reduction in the search depth, is a fatal pruning! Therefore, IDA * is faster than A * in most cases. It can be said that it is an optimized version of! For code, see Code4.cpp. At this point, it's in my realm ...... Ask the teacher to upgrade the realm ...... Also, there may be many omissions in the previous article. I hope the teacher can correct them.

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.