|
| 1 | +/* |
| 2 | + * Copyright (c) 2021, Christopher Friedt |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: MIT |
| 5 | + */ |
| 6 | + |
| 7 | +// name: n-queens-ii |
| 8 | +// url: https://leetcode.com/problems/n-queens-ii |
| 9 | +// difficulty: 3 |
| 10 | + |
| 11 | +#include <unordered_set> |
| 12 | +#include <vector> |
| 13 | + |
| 14 | +#ifndef BIT |
| 15 | +#define BIT(n) (1ULL << (n)) |
| 16 | +#endif |
| 17 | + |
| 18 | +using namespace std; |
| 19 | + |
| 20 | +class Solution { |
| 21 | +public: |
| 22 | + static inline unsigned popcount(unsigned n) { return __builtin_popcount(n); } |
| 23 | + |
| 24 | + static inline unsigned diag_up(unsigned r, unsigned c) { return r + c; } |
| 25 | + |
| 26 | + static inline unsigned diag_down(unsigned N, unsigned r, unsigned c) { |
| 27 | + return N - r - 1 + c; |
| 28 | + } |
| 29 | + |
| 30 | + void Q(uint8_t n, unordered_set<string> &paths, string path, |
| 31 | + uint16_t used_cols, uint16_t used_diag_up, uint16_t used_diag_down) { |
| 32 | + |
| 33 | + static const array<uint16_t, 10> nsoln = {0, 1, 0, 0, 2, |
| 34 | + 10, 4, 40, 92, 352}; |
| 35 | + |
| 36 | + uint8_t row = path.size() / n; |
| 37 | + |
| 38 | + if (row == n) { |
| 39 | + /* TODO: insert reflections, rotations.. */ |
| 40 | + paths.insert(path); |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + for (int col = n - 1; col >= 0; --col) { |
| 45 | + if (BIT(col) & used_cols) { |
| 46 | + continue; |
| 47 | + } |
| 48 | + |
| 49 | + auto upd = diag_up(row, col); |
| 50 | + if (BIT(upd) & used_diag_up) { |
| 51 | + continue; |
| 52 | + } |
| 53 | + |
| 54 | + auto downd = diag_down(n, row, col); |
| 55 | + if (BIT(downd) & used_diag_down) { |
| 56 | + continue; |
| 57 | + } |
| 58 | + |
| 59 | + string row_str(n, '.'); |
| 60 | + row_str[col] = 'Q'; |
| 61 | + |
| 62 | + Q(n, paths, path + row_str, used_cols | BIT(col), used_diag_up | BIT(upd), |
| 63 | + used_diag_down | BIT(downd)); |
| 64 | + |
| 65 | + if (nsoln[n] == paths.size()) { |
| 66 | + break; |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + |
| 71 | + int totalNQueens(int n) { |
| 72 | + unordered_set<string> paths; |
| 73 | + |
| 74 | + Q(n, paths, "", 0, 0, 0); |
| 75 | + |
| 76 | + return paths.size(); |
| 77 | + } |
| 78 | +}; |
0 commit comments