From 1bc28e5b15a6d26b3789446d8f2721d45f33e9ee Mon Sep 17 00:00:00 2001 From: Ashwani Date: Thu, 6 Oct 2022 14:23:43 +0530 Subject: [PATCH] Modified N-Queens in better and clean code --- Hard/N-Queens.cpp | 67 +++++++++++++++++++++-------------------------- 1 file changed, 30 insertions(+), 37 deletions(-) diff --git a/Hard/N-Queens.cpp b/Hard/N-Queens.cpp index cfdc7d7..f4386f7 100644 --- a/Hard/N-Queens.cpp +++ b/Hard/N-Queens.cpp @@ -1,3 +1,5 @@ +//Code by Ashwani-de + // Problem statement :- // 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. @@ -16,70 +18,61 @@ using namespace std; class Solution { + vector> ans; + public: - bool isSafe(int row, int col, vector &board, int n) + bool isSafe(int r, int c, vector &v, int n) { - int duprow = row; - int dupcol = col; - while (row >= 0 && col >= 0) + for (int i = 0; i <= r; i++) { - if (board[row][col] == 'Q') - { + if (v[i][c] == 'Q') return false; - } - row--; - col--; } - col = dupcol; - row = duprow; - while (col >= 0) + + int row = r, col = c; + + while (row >= 0 && col >= 0) { - if (board[row][col] == 'Q') - { + if (v[row][col] == 'Q') return false; - } - col--; + row--, col--; } - col = dupcol; - row = duprow; - while (row < n && col >= 0) + + row = r, col = c; + + while (row >= 0 && col < n) { - if (board[row][col] == 'Q') - { + if (v[row][col] == 'Q') return false; - } - row++; - col--; + row--, col++; } return true; } - void solve(int col, vector &board, vector> &ans, int n) + + void helper(int r, int n, vector &v) { - if (col == n) + if (r == n) { - ans.push_back(board); + ans.push_back(v); return; } for (int i = 0; i < n; i++) { - if (isSafe(i, col, board, n)) + if (isSafe(r, i, v, n)) { - board[i][col] = 'Q'; - solve(col + 1, board, ans, n); - board[i][col] = '.'; + v[r][i] = 'Q'; + helper(r + 1, n, v); + v[r][i] = '.'; } } } vector> solveNQueens(int n) { - vector board(n); - vector> ans; + vector v; string s(n, '.'); for (int i = 0; i < n; i++) - { - board[i] = s; - } - solve(0, board, ans, n); + v.push_back(s); + helper(0, n, v); return ans; } };