knight_tour.cpp 1.5 KB
Newer Older
S
stepfencurryxiao 已提交
1
#include <iostream>
2
#define n 8
3 4 5

/**
A knight's tour is a sequence of moves of a knight on a chessboard
6 7 8
such that the knight visits every square only once. If the knight
ends on a square that is one knight's move from the beginning
square (so that it could tour the board again immediately, following
9 10 11
the same path), the tour is closed; otherwise, it is open.
**/

12 13
using std::cin;
using std::cout;
14

15 16
bool issafe(int x, int y, int sol[n][n]) {
    return (x < n && x >= 0 && y < n && y >= 0 && sol[x][y] == -1);
17
}
18 19
bool solve(int x, int y, int mov, int sol[n][n], int xmov[n], int ymov[n]) {
    int k, xnext, ynext;
20

21
    if (mov == n * n)
22 23
        return true;

24 25 26
    for (k = 0; k < 8; k++) {
        xnext = x + xmov[k];
        ynext = y + ymov[k];
27

28 29
        if (issafe(xnext, ynext, sol)) {
            sol[xnext][ynext] = mov;
30

31 32 33 34 35
            if (solve(xnext, ynext, mov + 1, sol, xmov, ymov) == true)
                return true;
            else
                sol[xnext][ynext] = -1;
        }
36 37 38
    }
    return false;
}
39 40
int main() {
    // initialize();
41 42

    int sol[n][n];
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
    int i, j;
    for (i = 0; i < n; i++)
        for (j = 0; j < n; j++) sol[i][j] = -1;

    int xmov[8] = {2, 1, -1, -2, -2, -1, 1, 2};
    int ymov[8] = {1, 2, 2, 1, -1, -2, -2, -1};
    sol[0][0] = 0;

    bool flag = solve(0, 0, 1, sol, xmov, ymov);
    if (flag == false)
        cout << "solution doesnot exist \n";
    else {
        for (i = 0; i < n; i++) {
            for (j = 0; j < n; j++) cout << sol[i][j] << "  ";
            cout << "\n";
58 59 60
        }
    }
}