diff --git a/cpp/2206/220604.cpp b/cpp/2206/220604.cpp new file mode 100644 index 0000000..accf400 --- /dev/null +++ b/cpp/2206/220604.cpp @@ -0,0 +1,48 @@ +#include +#include +#include + +/** + * 51. N-Queens + * The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other. + * Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. + * Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively. + */ + +class Solution { +public: + static std::vector> solveNQueens(const int n) { + std::vector> ret; + + bool xs[10]{}, ds[20]{}, sds[20]{}, G[10][10]{}; + std::function dfs = [&](int d) { + if (d >= n) { + std::vector ans(n); + for (int i = 0; i < n; ++i) { + std::string s(n, ' '); + for (int j = 0; j < n; ++j) + s[j] = G[i][j] ? 'Q' : '.'; + ans[i] = s; + } + ret.push_back(ans); + return; + } + for (int i = 0; i < n; ++i) { + if (xs[i] || ds[d - i + 10] || sds[d + i]) + continue; + G[d][i] = xs[i] = ds[d - i + 10] = sds[d + i] = true; + dfs(1 + d); + G[d][i] = xs[i] = ds[d - i + 10] = sds[d + i] = false; + } + }; + + dfs(0); + + return ret; + } +}; + +int main() { + auto ret = Solution::solveNQueens(4); + return 0; +} diff --git a/cpp/2206/CMakeLists.txt b/cpp/2206/CMakeLists.txt index ca6a8f1..0d5f52f 100644 --- a/cpp/2206/CMakeLists.txt +++ b/cpp/2206/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2206) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2206 220602-CN.cpp) +ADD_EXECUTABLE(2206 220604.cpp)