求优化方案
查看原帖
求优化方案
133693
AnchorPoint2007楼主2022/5/1 16:20
#include <iostream>
#include <vector>
#include <map>
#include <cstring>
#include <algorithm>

using namespace std;

int num;
typedef vector<map<int, bool> > CheckerBoard;
vector<CheckerBoard> results;

void output(CheckerBoard checkerBoard) {
    vector<int> out;
    out.reserve(num);
    for (int i = 0; i < num; i++) {
        for (int j = 0; j < num; j++) {
            if (checkerBoard[i][j]) {
                out.push_back(j + 1);
            }
        }
    }
    for (int i: out) {
        printf("%d ", i);
    }
    printf("\n");
}

bool check(CheckerBoard checkerBoard, int row = num) {
    bool hashRow[row], hashCol[num];
    map<int, bool> hashDiagonal1, hashDiagonal2;
    memset(hashRow, false, sizeof(hashRow));
    memset(hashCol, false, sizeof(hashCol));
    for (int i = 0; i < row; i++) {
        for (int j = 0; j < num; j++) {
            if (checkerBoard[i][j]) {
                if (hashRow[i] || hashCol[j] || hashDiagonal1[i + j] || hashDiagonal2[i - j]) {
                    return false;
                }


                hashRow[i] = true;
                hashCol[j] = true;
                hashDiagonal1[i + j] = true;
                hashDiagonal2[i - j] = true;
            }
        }
    }
    return true;
}

void dfs(CheckerBoard checkerboard) {
    const int level = checkerboard.size();
    if (level == num) {
        if (check(checkerboard))
            results.push_back(checkerboard);

        return;
    } else {
        map<int, bool> tmpMap;
        checkerboard.push_back(tmpMap);
        for (int i = 0; i < num; i++) {
            checkerboard[level][i] = true;
            if(check(checkerboard, level)) {
                dfs(checkerboard);
            }
            checkerboard[level][i] = false;
        }
    }
}

int main() {
    cin >> num;
    CheckerBoard checkerBoard;
    checkerBoard.reserve(14);
    checkerBoard.clear();
    dfs(checkerBoard);
    unsigned len = results.size();
    for (int i = 0; i < len && i < 3; i++) {
        output(results[i]);
    }
    cout << len << endl;
    return 0;
}

实在不想用数组……

2022/5/1 16:20
加载中...