ACM: Search algorithm topics (3)--Heuristic search __ACM

Source: Internet
Author: User
Topic Source:
HihoCoder1312
Topic Description:
Give a nine-Sudoku puzzle game, to complete the puzzle at least need a certain number of steps.
Answer:
• Rules:

First briefly explain the rules of the game.

The chess game is as follows:


The nine lattice is placed with 8 pieces marked with different numbers, one of which is empty, by moving the pieces and making the numbers orderly, the game is done as follows:


During the move, only pieces that are adjacent to the empty position can be moved and can only be moved to a blank position. In the following example, you can complete the Game 6 times by moving:


These are the rules of the game.

Coding
The idea of the subject is still relatively simple. By Dijkstra algorithm, the shortest path of each board state to the final state can be computed. The shortest path here is defined as the minimum number of moves. The first question, then, is to record the status of the chess game in some way. The method is as follows:
Assuming the blank position is the number 9, then the number of different chess games is: 9. = 362880 species. If all the permutations are sorted in a dictionary order, then each permutation will have a unique number. Therefore, the number 1 is arranged as: 123456789, and the number 362880 is arranged as: 987654321. So the problem now is to give an arrangement to find out the number of it in the dictionary sequence. This problem can be solved by using a method called Cantor expansion, as follows:
For an arrangement: s[1,2,... 9], defines the sequence a[1,2,..., 9], wherein A[i] represents the sequence s[i+1, i+2, ... 9] The number of values smaller than a[i], for example, arrange 9 1 2 3 6 4 7 8-5 corresponding a[i] sequences are: 8 0 0 2 0 1 0.0.
After the a[i] sequence is given, the ordinal number of the array s corresponds to:
X = a[1] * (9-1)! + a[2] * (9-2)! + ... + a[9] * (9-9)!
The goal of the game is: 1 2 3 4 5 6 7 8 9, the corresponding serial number is 1.

Decoding
After we know the coding method, we also need to know how to find the corresponding arrangement result given the number x. This process is the reverse process of Cantor's unfolding, which can be called "reverse Cantor". The method is as follows:
① x divided by (9-1)! Get quotient Q and remainder R.
② from 1,2,... 9 of the unused digits in the q+1 number, the number is s[1].
③ Order: X=r.
④ Repeat steps ①-③, in each iteration, make x divided by (9-2)!, (9-3)!, ..., (9-9)!, you can get the s[2], s[3]...s[9, and then get the corresponding arrangement results.

Here is an example of how to solve a 1-9 permutation, ranked No. 5000 in the permutation:
① Order: x=5000, X÷ (9-1)! = 0...........5000, Q=0 r=5000, the currently unused number has {1,2,3, 4,5,6,7,8,9}, select the 1th small number, that is 1, so s[1] = 1.
② Order: x=5000, X÷ (9-2)! = 0...........5000, Q=8 r=5000, the currently unused number has {2,3,4,5,6,7,8,9}, select the 1th small number, that is 2, so s[2] = 2.
③ Order: x=5000, X÷ (9-3)! = 6...........680, Q=6 r=680, the currently unused number has {3,4,5,6,7,8,9}, select the 7th small number, that is 9, so s[3] = 9.
④ Order: x=680, X÷ (9-4)! = 5...........80, Q=5 r=80, the currently unused number has {3,4,5,6,7,8}, select the 6th small number, that is 8, so s[4] = 8.
⑤ Order: x=80, X÷ (9-5)! = 3...........8, Q=3 r=8, the currently unused number has {3,4,5,6,7}, select the 4th small number, that is 6, so s[5] = 6.
⑥ Order: x=8, X÷ (9-6)! = 1...........2, Q=1 r=2, the currently unused number has {3,4,5,7}, select the 2nd small number, that is 4, so s[6] = 4.
⑦ Order: x=2, X÷ (9-7)! = 1...........0, Q=1 r=0, the currently unused number has {3,5,7}, select the 2nd small number, that is 5, so s[7] = 5.
⑧ Order: x=0, X÷ (9-8)! = 0...........0, Q=0 r=0, the currently unused number has {3,7}, select the 1th small number, that is 3, so s[8] = 3.
⑨ Order: x=0, X÷ (9-9)! = 0...........0, Q=0 r=0, the currently unused number has {7}, select the 1th small number, that is 7, so s[9] = 7.
As a result, the No. 5000 ranked results are: 1 2 9 8 6 4 5 3 7.

Search
After you know how to represent the status of a chess game as a number, you can search. We can abstract the whole game into a forward graph, and the points in the graph are the different chess states. And if two states can be converted to each other by moving the pieces one at a time, then the two points consist of a single, 1-length side:


After the work of building a map is complete, there are two ways to search:
Method one: From the end point to the starting point
With the final situation-State 1 as the starting point, using the Dijkstra algorithm to search, you can know each state to the final state of the shortest distance, and then given the initial state of the next, you can directly find the corresponding minimum number of moves. Once this method is searched, the initial state of all input can be answered directly.

Method Two: From the beginning to the end
You can also search for the shortest distance to the end point in the case of a given starting state. At this point, a search is required for each set of given starting positions. In order to improve the efficiency, a "heuristic" search method can be used to improve the Dijkstra algorithm. The method is as follows:
The idea of heuristic search is: Design an evaluation function f, use the evaluation function for each point evaluation, and then in the search process to prioritize the results of better points. This gives a higher probability of first finding the shortest path to the end point.
The evaluation function F is made up of two parts: F = g + H, where g indicates the shortest path length from the starting point to the current point, the initial state is 0, and the G is assigned in the search process; H represents the shortest distance path from the current point to the endpoint, and function h needs to be estimated before searching.
Two collections are maintained during the search: Openset and CloseSet, and two sets are empty at the initial state. The search steps are as follows:
① sets the G value of the starting point to 0 and sets it to the current point.
② Type the current point into the CloseSet.
③ searches all points adjacent to the current point, if the point is already in the CloseSet, the operation is not done, and if the point is in Openset, then its G value is updated to compare the G value of the current point with 1 and the G value of the critical point, taking the lesser; If the critical point is not in Openset, The G value of the point is set to the current point G value plus 1 and then added to the Openset.
④ Select the point with the lowest F value in the Openset as the current point.
⑤ repeatedly perform steps ②-④ until Openset is empty or the focus has been added to CloseSet, where the shortest path from start to finish is found.

Note In order to ensure the correctness of the algorithm, the function h for each point must not be greater than the actual distance to the endpoint. Otherwise, when you select the current search point from Openset, you may have an error, resulting in the inability to get the optimal solution. For this subject, we can define the sum of the Manhattan distances in which the function H is: the current position of 1-8 of the 8 digits in the current state to the 8 corresponding positions in the target State. Because each move will change the position of a piece, resulting in the position of the pawn to the target location of the Manhattan distance increase or decrease, if each move is to reduce the moving pieces to the target location of the Manhattan distance, then the total number of moves is 8 pieces to the target location of the Manhattan distance of the sum. If some of the moves in the process will make the moving pieces of the Manhattan distance larger, then the total number of moves more. So it is correct to define the function H.

The following code uses method one.

input and output format:
Input:Line 1th: 1 positive integer t, representing the number of data sets, then there is the T Group data, each group of data has 3 rows, 3 integers per row, contains 0-8, each number appears only once, where 0 represents the vacancy.
Output:1th.. T-row: 1 integers per line representing the number of steps for the data solution for the group. If no solution output "no solution!"

Data range:
1≤t≤8

Program code:

/****************************************************//* file:hiho_week_100 * * Author : Zhang Yufei * * * date:2016-05-30 * * description:hihocod ER ACM program. (submit:g++) *//****************************************************/#include <stdio.h> #include <
Stdlib.h> #define NUM 362880 typedef struct NODE1 vertex;

typedef struct NODE2 Edge;
 * * Define structure to store the node of graph.
 * Parameters: * @distance: The distance between the current node and the start node.
 * @edges: The link list of the nodes which are adjacent with this node.
 * @tag: Mark If the node has been visited.
	* * typedef struct NODE1 {int status;
	int index;
	int distance;
	Edge *edges;
int tag;

} vertex;
 * * Define structure to store the edges of the graph.
 * Parameters: * @index: The end point of this edge.
 * @next: The next pointer. * * typedef struct NODE2 {vertex* V;
struct Node2 *next;

} Edge;
Record the graph.

Vertex Graph[num];
Record the multiply value.

int multiply[9] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320};
The record map.

int map[9];
Record the Set.

Vertex *heap[num + 1];
The size of heap.

int heap_cnt;
 * * This function compare the distance of the 2 elements in heap.
 * Parameters: * @a & @b:the 2 elements to compare. * Returns: * If @a is greater than @b, Returns 1;
 Or if @a is equal to @b, returns 0;
 * or returns-1;
	*/INT cmp (int a, int b) {if (heap[b]->distance = = 1) {return-1;
	else if (heap[a]->distance = = 1) {return 1;
	}else if (Heap[a]->distance > Heap[b]->distance) {return 1;
	}else if (heap[a]->distance = = heap[b]->distance) {return 0;
	else {return-1;
 }/* This function adjusts the array into a heap.
 * Parameters: * @root: The root of heap.
 * Returns: * None.
	*/void min_heapify (int root) {int min_index = root; if (Root * 2 <= HEAP_CNT) {if (CMP (Min_index, 2 * root) > 0) {min_index = 2 * root;
		} if (Root * 2 + 1 <= heap_cnt) {if (CMP (Min_index, 2 * root + 1) > 0) {min_index = 2 * root + 1;
		} if (Min_index!= root) {vertex *swap = Heap[root];
		Heap[root] = Heap[min_index];
		Heap[min_index] = swap;
		Heap[root]->index = root;
		Heap[min_index]->index = Min_index;
	Min_heapify (Min_index);
 } * * This node adjust the heap after update the distance of node.
 * Parameters: * @index: the element to update.
 * Returns: * None.
			*/void Update (int index) {while (Index > 1) {if (CMP (index, INDEX/2) < 0) {vertex *swap = Heap[index];
			Heap[index] = HEAP[INDEX/2];
			HEAP[INDEX/2] = swap;
			Heap[index]->index = index;
			Heap[index/2]->index = INDEX/2; 
		Index/= 2;
		} else {break;
 }}/* This function removes the "top" element from heap.
 * Parameters: * None.
 * Returns: * the element removed. */vertex* Remove (void) {Vertex *r = heap[1];
	HEAP[1] = heap[heap_cnt];
	Heap[1]->index = 1;
	
	heap_cnt--;
	
	Min_heapify (1);
return R;
 /* * This function transports the map into status number.
 * parameters£º* None.
 * Returns: * The status number.
	*/int Get_status_from_map (void) {int status = 0;
	
	int tag[10] = {0};
		for (int i = 0; i < 9; i++) {int cnt = 0;
			for (int j = 1; j < Map[i]; J +) {if (tag[j] = = 0) {cnt++;
		Status = + cnt * Multiply[8-i];
	Tag[map[i]] = 1;
} return status;
 /* * This function transports the status into map.
 * Parameters: * @status: the current status.
 * Returns: * None.
	*/void Get_map_from_status (int status) {int tag[10] = {0};
		for (int i = 0; i < 9; i++) {int s = status/multiply[8-i];
		int cnt = 0;
				for (int j = 1; J < + j) {if (tag[j] = = 0) {cnt++; if (CNT >

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.