Advertisement
sb8623

Untitled

Jan 16th, 2024
744
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.64 KB | Source Code | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. class Nqueens {
  7.     int sol_count;
  8.     int board_size;
  9.     vector<int> solution_board;
  10. public:
  11.     Nqueens(int size) : board_size(size), sol_count(0) {}
  12.  
  13.     bool is_valid(vector<int> board, int row_idx) {
  14.         for (int i =0; i < board.size(); i++) {
  15.             if (row_idx == board[i]) return false;
  16.         }
  17.         int curr_index = board.size();
  18.         for (int i = 0; i < board.size(); i++) {
  19.             if (board[i] + (curr_index-i) == row_idx || board[i] - (curr_index-i) == row_idx) return false;
  20.         }
  21.         return true;
  22.     }
  23.  
  24.     void print_board(vector<int> board) {
  25.         for (int i = 0; i < board.size(); i++) {
  26.             for (int j = 0; j < board.size(); j++) {
  27.                 if (j == board[i]) {
  28.                     cout << "Q ";
  29.                 }
  30.                 else cout << "- ";
  31.             }
  32.             cout << endl;
  33.         }
  34.     }
  35.  
  36.     void search(vector<int> board, int curr_idx) {
  37.         if (curr_idx == board_size) {
  38.             print_board(board);
  39.             sol_count++;
  40.             cout << "Solution: " << sol_count << endl;
  41.         }
  42.  
  43.         for (int i = 0; i < board_size; i++) {
  44.             if (is_valid(board, i)) {
  45.                 board.push_back(i);
  46.                 search(board, curr_idx+1);
  47.                 board.pop_back();
  48.             }
  49.         }
  50.     }
  51.  
  52.     void goal_search() {
  53.         search(solution_board, 0);
  54.     }
  55.  
  56.     void print_count() {
  57.         cout << "Total solutions: " << sol_count << endl;
  58.     }
  59.  
  60. };
  61.  
  62. int main() {
  63.     Nqueens nq(15);
  64.     nq.goal_search();
  65.     nq.print_count();
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement