第一次挑战写回溯,虽然大部分对了但还是有一个遗憾的TLE

P1219 [USACO1.5] 八皇后 Checker Challenge

GouRuitong @ 2024-03-17 17:26:50

请问这个还有地方能救一下吗(不大改的情况下),不想留下遗憾orz

#include <iostream>
#include <vector>
using namespace std;

bool check(vector<int> board, int n, int row, int col) {
    for (int i = 0; i < board.size(); i++) {
        if (board[i] == col || board[i] - col == i + 1 - row || i + 1 + board[i] == row + col)
            return false;
    }
    return true;
}

void backtrack(vector<vector<int>> &ans, vector<int> &board, int n, int row) {
    if (board.size() == n) {
        ans.push_back(board);
        return;
    }
    for (int col = 1; col <= n; col++) {
        if (check(board, n, row, col)) {
            board.push_back(col);
            backtrack(ans, board, n, row + 1);
            board.pop_back();
        }
    }
}

int main() {
    int n;
    cin >> n;
    vector<int> board = {};
    vector<vector<int>> ans = {};
    backtrack(ans, board, n, 1);
    int k = 3;
    for (auto e1 : ans) {
        for (auto e2 : e1) {
            cout << e2 << ' ';
        }
        cout << endl;
        k--;
        if(!k)
            break;
    }
    cout<<ans.size();
    return 0;
}

by XuYueming @ 2024-03-17 17:59:11

check 加引用 @GouRuitong


by GouRuitong @ 2024-03-17 18:03:23

@XuYueming 过了,谢谢!!


|