问题的类别是回溯(backtrace).
回溯通常用递归实现。回溯中注意边界问题,避免越界。同时,剪枝可以减少case数量。
具体看leetcode这里
// .h
#ifndef AGORITHM_NQUEENS_H
#define AGORITHM_NQUEENS_H
#include <string>
#include <vector>
class NQueens {
public:
static void test_nqueens();
static std::vector<std::vector<std::string>> solveNQueens(int n);
private:
static void visit(std::vector<std::vector<int>> &vis, std::vector<std::vector<int>> &mat, int r, int c,
std::vector<std::vector<std::string>> &ans);
static void generateAnswer(const std::vector<std::vector<int>> &mat, std::vector<std::vector<std::string>> &ans);
};
#endif //AGORITHM_NQUEENS_H
// .cpp
#include <sstream>
#include <iostream>
#include "NQueens.h"
using namespace std;
std::vector<std::vector<std::string>> NQueens::solveNQueens(int n) {
vector<vector<int>> vis(4, vector<int>(n * 2, 0));
std::vector<std::vector<std::string>> ans;
vector<vector<int>> mat(n, vector<int>(n, 0));
for (int i = 0; i < n; i++) {
visit(vis, mat, 0, i, ans);
}
// int nAnswer = ans.size();
return ans;
}
void NQueens::visit(std::vector<std::vector<int>> &vis, std::vector<std::vector<int>> &mat, int r, int c,
std::vector<std::vector<std::string>> &ans) {
const int N = mat.size();
if (!vis[0][r] && !vis[1][c] && !vis[2][r + c] && !vis[3][(r - c + 2 * N) % (2 * N)]) {
// mark
vis[0][r] = 1; // kth row
vis[1][c] = 1; // mth column
vis[2][r + c] = 1;
vis[3][(r - c + 2 * N) % (2 * N)] = 1;
mat[r][c] = 1;
if (r == N - 1) {
generateAnswer(mat, ans);
} else {
for (int j = 0; j < N; j++) {
visit(vis, mat, r + 1, j, ans);
}
}
vis[0][r] = 0;
vis[1][c] = 0;
vis[2][r + c] = 0;
vis[3][(r - c + 2 * N) % (2 * N)] = 0;
mat[r][c] = 0;
}
}
void NQueens::generateAnswer(const std::vector<std::vector<int>> &mat, std::vector<std::vector<std::string>> &ans) {
const int N = mat.size();
std::vector<std::string> vec;
for (int i = 0; i < N; i++) {
std::string s;
for (int j = 0; j < N; j++) {
if (mat[i][j]) {
s += "Q";
} else {
s += ".";
}
}
vec.emplace_back(s);
}
ans.emplace_back(vec);
}
void NQueens::test_nqueens() {
int n;
std::cin >> n;
auto ans = solveNQueens(n);
std::cout << "nanswer: " << ans.size() / 4 << std::endl;
for (auto &an : ans) {
for (const auto &s : an) {
std::cout << s << "\n";
}
std::cout << std::endl;
}
}
网友评论