From 04b39320906fe08d6d0f9342bb959872d7893830 Mon Sep 17 00:00:00 2001 From: lakshay451 <89472581+lakshay451@users.noreply.github.com> Date: Fri, 30 Sep 2022 14:05:05 +0530 Subject: [PATCH] Added solution for Leetcode - 51 --- N-Queens.cpp | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 N-Queens.cpp diff --git a/N-Queens.cpp b/N-Queens.cpp new file mode 100644 index 0000000..c35b325 --- /dev/null +++ b/N-Queens.cpp @@ -0,0 +1,75 @@ +class Solution { +private: + vector> Help(int n) { + vector> ans; + vector> board(n, vector(n,0)); + solve(0,board,ans,n); + return ans; + } + + bool isSafe(int r, int c, vector> &board, int n){ + int x = r; + int y = c; + + // check for column + while(x >= 0){ + if(board[x][y] == 1) return false; + x--; + } + + x = r, y = c; + // check one diagonal + if(x>0){ + while( x>=0 && y0){ + while( x>=0 && y>=0){ + if(board[x][y] == 1) return false; + x--; + y--; + } + } + + return true; + } +private: + void solve(int row, vector> &board, vector> &ans, int n){ + // base case + if(row == n){ + vector temp; + for(int i=0; i> solveNQueens(int n) { + vector> ans; + vector> board(n, vector(n,0)); + solve(0,board,ans,n); + return ans; + } +};