Sicily 1153. Horse traveling Problems

Source: Internet
Author: User

I. Description

There is a horse in a position in an 8*8 board. If it goes through 29 steps, it passes through each position except the start point, this is a travel route called a horse by law. We try to design an algorithm to find a travel route from a given starting point.

To facilitate the expression of a chessboard, we follow the number of squares from top to bottom, from left to right, as shown below:

1 2 3 4 5 6 7 8

9 10 11 12 13 14 15 16

17 18 19 20 21 22 23 24

25 26 27 28 29 30 31 32

33 34 35 36 37 38 39 40

41 42 43 44 45 46 48

49 50 51 52 53 54 55 56

57 58 59 60 61 62 63 64

The path of a horse is a "Day". For example, when the horse is in the position of 15, it can reach 2, 4, 7, 11, 19, 23, 26, and 28. However, it is stipulated that the horse cannot jump out of the Board. For example, from position 1 can only reach 9 and 14.

Input

 

The input has several rows. Each line has an integer N (1 <=n <= 30), indicating the start point of the horse. The last line ends with-1, which does not need to be processed.

 

Output

 

Find a travel route for each input start point. Output a row with 30 integers. The number of the checkerboard square that the horse passes by is given in sequence from the start point. Adjacent numbers are separated by a space.

 

Sample Input

 

4

-1

Sample output

 

Note: If the start point is different from the input given, it is considered wrong to repeatedly pass through the same square or some squares are not passed.

 

Ii. algorithm ideas and main data structures

    • Algorithm idea: This question uses DFS to find a path, because according to the description of the question, we can see that the depth of the path is not very large, so deep search is a better method. Use recursion to achieve deep search.
    • Main data structure: Here, struct is used to save the internal values of nodes and vector is used to save nodes.

 

Iii. Detailed solutions

    1. First, because the size of the Board is increased, deep searches without pruning will obviously time out. We can see from the tree structure that the number of lower-layer subnodes is also reduced when the upper-layer subnodes are reduced. Therefore, the idea here is to ensure that the number of nodes that can be followed by a smaller number of nodes can be expanded first, that is, if the current node is the node, the number of nodes that can be followed. Therefore, we need to calculate the number of scalable locations of the next possible node, and then sort the nodes by the number of locations to give priority to the positions with fewer locations.

2. location processing, because the location representation of the original board is represented by a number, which is not suitable for our operations, therefore, convert the representative number of the chessboard into a subscript of an 8*8 array for processing:

X = (n-1)/8;

Y = (n-1) % 8;

3. Horse moving analysis: Because the horse must follow the "day" route, there will be a maximum of eight horse moving positions, which are as follows:

Position (-1, 2), position (-2, 1), position (-2,-1), position (-1,-2 ),

Position (1,-2), position (2,-1), position (2, 1), position (1, 2)

After each move, there may be eight locations. You need to determine the validity of these locations:

Bool isvalid (int x, int y ){

Return x> = 0 & Y> = 0 & x <= 7 & Y <= 7;

}

That is, the position must be in the chessboard.

 

4. Path record: because the results will be obtained in 64 steps, that is to say, each step represents a location, you only need to use an array containing 64 elements to record the location.

Int route [64];

When taking a new path, you only need to change the number at the corresponding position of the number of steps to the number at the corresponding position:

Route [STEP] = 8 * ytemp + xtemp + 1;

 

5. at each current location, the next location where the node can go is obtained. After obtaining these locations, these locations are used to view the number of possible extension locations for the current node and sort them according to the number, save it in a vector and find the next position from the vector.

If (isvalid (xtemp, ytemp )){

Int canmovepolicitionnum = getcanmovepositionnum (xtemp, ytemp );

If (canmovepolicitionnum! = 0)

Partition ition. push_back (position (xtemp, ytemp, canmovepolicitionnum ));

}

Sort (partition ition. Begin (), partition ition. End (), CMP );

 

Code:

#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>#include <vector>using namespace std;bool visited[8][8];bool success = false;int roate[64];struct Position{    Position(int x_ = 0, int y_ = 0, int num = 0): x(x_), y(y_), canMovePoisitionNum(num) { }                         int x;    int y;    int canMovePoisitionNum;}; Position Move[8] = {Position(1, -2), Position(2, -1), Position(2, 1), Position(1, 2),                    Position(-1, 2), Position(-2, 1), Position(-2, -1), Position(-1, -2)};bool isValid(int x, int y) {    return x >= 0 && y >= 0 && x <= 7 && y <= 7;}int getCanMovePositionNum(int x, int y) {    int canMovePoisitionNum = 0;    for (int i = 0; i != 8; ++i) {        if(isValid(x + Move[i].x, y + Move[i].y))            canMovePoisitionNum++;    }    return canMovePoisitionNum;}bool cmp(const Position &a, const Position &b) {    return a.canMovePoisitionNum < b.canMovePoisitionNum;}void search(int step, int x, int y) {    vector<Position> poisition;    for (int i = 0; i != 8; ++i) {        int xTemp = x + Move[i].x;        int yTemp = y + Move[i].y;        if (isValid(xTemp, yTemp)) {            int canMovePoisitionNum = getCanMovePositionNum(xTemp, yTemp);            if (canMovePoisitionNum != 0)                poisition.push_back(Position(xTemp, yTemp, canMovePoisitionNum));        }    }    sort(poisition.begin(), poisition.end(), cmp);    for (int i = 0; i != poisition.size(); ++i) {        if (success)            return;        if (step == 63) {            success = true;            return;        }        if (!visited[poisition[i].x][poisition[i].y]) {            ++step;            roate[step] = 8 * poisition[i].x + poisition[i].y + 1;            visited[poisition[i].x][poisition[i].y] = true;            search(step, poisition[i].x, poisition[i].y);            visited[poisition[i].x][poisition[i].y] = false;            --step;        }    }}int main(int argc, char *argv[]){    int N, x, y;    while (scanf("%d", &N) && N != -1) {        roate[0] = N;        memset(visited, false, sizeof(visited));        success = false;        x = (N - 1) / 8;        y = (N - 1) % 8;        visited[x][y] = true;        search(0, x, y);        for (int i = 0; i != 63; i++)            printf("%d ", roate[i]);        printf("%d\n", roate[63]);    }    return 0;}

 

Sicily 1153. Horse traveling Problems

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.