|
| 1 | +/* Leet Code */ |
| 2 | +/* Title - N-Queens */ |
| 3 | +/* Created By - Akash Modak */ |
| 4 | +/* Date - 08/06/2023 */ |
| 5 | + |
| 6 | +// 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. |
| 7 | + |
| 8 | +// Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order. |
| 9 | + |
| 10 | +// Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively. |
| 11 | + |
| 12 | + |
| 13 | + |
| 14 | +// Example 1: |
| 15 | + |
| 16 | + |
| 17 | +// Input: n = 4 |
| 18 | +// Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]] |
| 19 | +// Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above |
| 20 | +// Example 2: |
| 21 | + |
| 22 | +// Input: n = 1 |
| 23 | +// Output: [["Q"]] |
| 24 | + |
| 25 | +class Solution { |
| 26 | +public: |
| 27 | + bool canPlace(vector<string> &r, int n, int i, int j){ |
| 28 | + for(int x=0;x<i;x++){ |
| 29 | + if(r[x][j]=='Q') return false; |
| 30 | + } |
| 31 | + int x=i,y=j; |
| 32 | + while(x>=0 and y>=0){ |
| 33 | + if(r[x][y]=='Q') return false; |
| 34 | + x--,y--; |
| 35 | + } |
| 36 | + x=i,y=j; |
| 37 | + while(x>=0 and y<n){ |
| 38 | + if(r[x][y]=='Q') return false; |
| 39 | + x--,y++; |
| 40 | + } |
| 41 | + return true; |
| 42 | + } |
| 43 | + bool nQueen(vector<vector<string>> &res, vector<string> &r, int n, int i){ |
| 44 | + if(i==n){ |
| 45 | + res.push_back(r); |
| 46 | + // intentionally making it false to generate all the cases |
| 47 | + return false; |
| 48 | + } |
| 49 | + for(int j=0;j<n;j++){ |
| 50 | + bool place=canPlace(r,n,i,j); |
| 51 | + if(place){ |
| 52 | + r[i][j]='Q'; |
| 53 | + bool success=nQueen(res,r,n,i+1); |
| 54 | + if(success) return true; |
| 55 | + r[i][j]='.'; |
| 56 | + } |
| 57 | + } |
| 58 | + return false; |
| 59 | + } |
| 60 | + vector<vector<string>> solveNQueens(int n) { |
| 61 | + vector<vector<string>> res; |
| 62 | + vector<string> r; |
| 63 | + string str; |
| 64 | + for(int i=1;i<=n;i++)str+='.'; |
| 65 | + for(int i=1;i<=n;i++)r.push_back(str); |
| 66 | + nQueen(res,r,n,0); |
| 67 | + return res; |
| 68 | + } |
| 69 | +}; |
0 commit comments