Sicily 1152. 简单的马周游问题

题目链接在此
这个题解未采用类似“启发式搜索”的做法。只是po一下代码。
更快捷的做法与详解见另一篇博文:《马的周游问题》



#include<iostream>
#include<vector>

using namespace std;

struct pos {
    int row;
    int col;

    pos() {}
    pos(int r, int c) : row(r), col(c) {}

    pos plus(pos a) {
        return pos(a.row + this->row, a.col + this->col);
    }
};

bool visited[31];
int printSeq[31];
const struct pos available[] = { pos(1, -2), pos(2, -1), pos(2, 1), pos(1, 2),
                                pos(-1, 2), pos(-2, 1), pos(-2, -1), pos(-1, -2) };

struct pos one_to_two_dim(int n) {
    int r = (n - 1) / 6 + 1;
    int c = (n - 1) % 6 + 1;
    return pos(r, c);
}

int two_to_one_dim(struct pos p) {
    if (p.row >= 1 && p.row <= 5 && p.col >= 1 && p.col <= 6)
        return (p.row - 1) * 6 + p.col;
    else
        return 0;
}

void DFS(int n, bool& isDone, int counter) {
    if (isDone)
        return;

    if (counter == 31) {
        isDone = true;

        bool spaceFlag = false;
        for (int i = 1; i <= 30; i++) {
            if (!spaceFlag)
                spaceFlag = true;
            else
                cout << ' ';

            cout << printSeq[i];
        }
        cout << endl;
    }
    else {
        for (int i = 0; i < 8; i++) {
            struct pos tmp = one_to_two_dim(n);
            int going_to = two_to_one_dim(tmp.plus(available[i]));

            if (going_to >= 1 && going_to <= 30 && visited[going_to] == false) {
                visited[going_to] = true;
                printSeq[counter] = going_to;
                counter++;

                DFS(going_to, isDone, counter);

                visited[going_to] = false;
                counter--;
            }
        }
    }   
}

int main() {
    int start;
    cin >> start;

    while (start != -1) {
        bool isDone = false;

        for (int i = 1; i <= 30; i++) {
            printSeq[i] = 0;
            visited[i] = false;
        }

        printSeq[1] = start;
        visited[start] = true;

        DFS(start, isDone, 2);

        cin >> start;
    }

    return 0;
}


你可能感兴趣的:(sicily)