MCPcopy Create free account
hub / github.com/chaharnishant11/CodeIn10DSA / Solution

Class Solution

Backtracking/Homework/nQueens.cpp:10–64  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

8// User function Template for C++
9
10class Solution{
11public:
12 vector<vector<int>> ans;
13
14 bool isSafe(vector<vector<int>>& board, int r, int c, int n){
15 for(int i=0;i<r;i++){
16 if(board[i][c]==1){
17 return false;
18 }
19 }
20
21 for(int i=r-1,j=c-1;i>=0 && j>=0; i--,j--){
22 if(board[i][j]==1){
23 return false;
24 }
25 }
26
27 for(int i=r-1,j=c+1;i>=0 && j<n; i--, j++){
28 if(board[i][j]==1){
29 return false;
30 }
31 }
32
33 return true;
34 }
35
36 void helper(vector<vector<int>>& board, int n,int r){
37 if (r==n){
38 vector<int> temp;
39 for(int i=0;i<n;i++){
40 for(int j=0;j<n;j++){
41 if(board[i][j]==1){
42 temp.push_back(j+1);
43 }
44 }
45 }
46 ans.push_back(temp);
47 return;
48 }
49
50 for(int i=0;i<n;i++){
51 if(isSafe(board,r,i,n)){
52 board[r][i]=1;
53 helper(board,n,r+1);
54 board[r][i]=0;
55 }
56 }
57 }
58 vector<vector<int>> nQueen(int n) {
59 // code here
60 vector<vector<int>> board(n,vector<int>(n,0));
61 helper(board,n,0);
62 return ans;
63 }
64};
65
66// { Driver Code Starts.
67

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected