N-Queen Problem | Practice | GeeksforGeeks

The n-queens puzzle is the problem of placing n queens on a (n×n) chessboard such that no two queens can attack each other.
Given an integer n, find all distinct solutions to the n-queens puzzle. Each solution contains distinct board configurations of the n-queens’ placement, where the solutions are a permutation of [1,2,3..n] in increasing order, here the number in the ith place denotes that the ith-column queen is placed in the row with that number. For eg below figure represents a chessboard [3 1 4 2].


 
Example 1:
Input:
1
Output:
[1]
Explaination:
Only one queen can be placed 
in the single cell available.
Example 2:
Input:
4
Output:
[2 4 1 3 ] [3 1 4 2 ]
Explaination:
These are the 2 possible solutions.
 
Your Task:
You do not need to read input or print anything. Your task is to complete the function nQueen() which takes n as input parameter and returns a list containing all the possible chessboard configurations in sorted order. Return an empty list if no solution exists.
 
Expected Time Complexity: O(n!)
Expected Auxiliary Space: O(n2) 
 
Constraints:
1 ≤ n ≤ 10 
0
bensonpx119817 hours ago
Using Unordered Set:
void backtrack(int col, int n, vector<vector<int>> &ans,vector<int> &temp, unordered_set<int> &rowSt, unordered_set<int> &posDiag, unordered_set<int> &negDiag)
    {
        if(col == n){
            ans.push_back(temp);
            return;
        }

        for(int row =0;row<n;row++){
            if(rowSt.find(row) == rowSt.end() && posDiag.find(col+row) == posDiag.end() &&
                negDiag.find(col-row) == negDiag.end()){
                    rowSt.insert(row);
                    posDiag.insert(col+row);
                    negDiag.insert(col-row);
                    temp.push_back(row+1);
                    backtrack(col+1,n,ans,temp,rowSt,posDiag,negDiag);
                    temp.pop_back();
                    rowSt.erase(row);
                    posDiag.erase(col+row);
                    negDiag.erase(col-row);
                }
        }
    }

    vector<vector<int>> nQueen(int n)
    {
        unordered_set<int> rowSt;
        unordered_set<int> posDiag;
        unordered_set<int> negDiag;
        vector<vector<int>> ans;
        vector<int> temp;

        backtrack(0,n,ans,temp,rowSt,posDiag,negDiag);
        return ans;
    }
0
insanelion3 days ago
class Solution{
    ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
     ArrayList<ArrayList<Integer>> nQueen(int n) {
        // code here
        boolean col[] = new boolean[n];
        boolean ld[] = new boolean[2*n-1];
        boolean rd[] = new boolean[2*n-1];
        ArrayList<Integer> list = new ArrayList<>();
        fill(0,col,n,list,ld,rd);
        return ans;
    }
    void fill(int x,boolean col[],int n,ArrayList<Integer> list,
    boolean ld[],boolean rd[]) {
        if(x==n) {
            ans.add(new ArrayList<>(list));
            return;
        }
        for(int i=0;i<n;i++) {
            if(col[i])
            continue;
            int left = i-x;
            int right = i+x;
            if(left<0)
            left = Math.abs(left)+n-1;
            if(ld[left] || rd[right])
            continue;
            ld[left] = true;
            rd[right] = true;
            col[i] = true;
            list.add(i+1);
            fill(x+1,col,n,list,ld,rd);
            list.remove(list.size()-1);
            col[i] = false;
            ld[left] = false;
            rd[right] = false;
        }
    }
}
0
insanelion3 days ago
class Solution{
    ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
     ArrayList<ArrayList<Integer>> nQueen(int n) {
        // code here
        boolean col[] = new boolean[n];
        boolean visited[][] = new boolean[n][n];
        ArrayList<Integer> list = new ArrayList<>();
        fill(0,visited,col,n,list);
        return ans;
    }
    void fill(int x,boolean visited[][],boolean col[],int n,ArrayList<Integer> list) {
        if(x==n) {
            ans.add(new ArrayList<>(list));
            return;
        }
        for(int i=0;i<n;i++) {
            if(col[i])
            continue;
            boolean test = diagonal(visited,x,i,n);
            if(test)
            continue;
            visited[x][i] = true;
            col[i] = true;
            list.add(i+1);
            fill(x+1,visited,col,n,list);
            list.remove(list.size()-1);
            visited[x][i] = false;
            col[i] = false;
        }
    }
    boolean diagonal(boolean visited[][],int x,int y,int n) {
        boolean left = false;
        boolean right = false;
        
        for(int i=x,j=y;i>=0&&j>=0;i--,j--)
        left = left||visited[i][j];
        
        for(int i=x,j=y;i>=0&&j<n;i--,j++)
        right = right||visited[i][j];
        
        return right||left;
    }
}
+1
rp214 days ago
Concise approach, have a look at this!!
class Solution {
    int n;
    bool row[12], d1[22], d2[22];
    vector<vector<int>> res;
    vector<int> v;
public:
    vector<vector<int>> nQueen(int n) {
        this -> n = n;
        memset(row, 0, 12);
        memset(d1, 0, 22);
        memset(d2, 0, 22);
        res.clear();
        recur(1);
        return res;
    }
    
    void recur(int c) {
        if(c > n) {
            res.push_back(v);
            return;
        }
        
        for(int r = 1; r <= n; r++) {
            if(row[r] || d1[r + c] || d2[r - c + n]) continue;
            row[r] = d1[r + c] = d2[r - c + n] = 1;
            v.emplace_back(r);
            recur(c + 1);
            row[r] = d1[r + c] = d2[r - c + n] = 0;
            v.pop_back();
        }
    }
};
0
riturajmishra4514 days ago
class Solution{public:
   bool isSafe(int row,int col,int n,vector<vector<int>> &board){              //leftwards       int drow=row,dcol=col;       while(col>=0){           if(board[row][col]==1) return false;           col--;       }              //Upwards Left Diagonal       row=drow;col=dcol;       while(col>=0 and row>=0){           if(board[row][col]==1) return false;           col--;           row--;       }              //Downwards Left Diagonal       row=drow;col=dcol;       while(col>=0 and row<n){           if(board[row][col]==1) return false;           col--;           row++;       }              return true;   }
   void nqueenHelper(int col,vector<vector<int>> &ans,vector<int> &arr,int n,   vector<vector<int>> &board){              if(col == n){           ans.push_back(arr);           return;       }              for(int row=0;row<n;row++){                      if(isSafe(row,col,n,board) and board[row][col]==0){                              arr.push_back(row+1);               board[row][col] = 1;               nqueenHelper(col+1,ans,arr,n,board);               board[row][col] = 0;               arr.pop_back();                          }       }   }
   vector<vector<int>> nQueen(int n) {       vector<vector<int>> board(n,vector<int>(n,0));       vector<vector<int>> ans;       vector<int> arr;       nqueenHelper(0,ans,arr,n,board);       return ans;   }};
0
rohankr200215 days ago
#User function Template for python3
def black(i,j,notpos,n):
    #black all positions below i,j
    for ii in range(i,n):
        notpos[ii][j] += 1
    #black diagonally down and right
    for ii in range(j,n):
        if i + ii - j < n:
            notpos[i + ii - j][ii] += 1
    #black diagonally down and left 
    for ii in range(j):
        if i + j - ii < n:
            notpos[i + j - ii][ii] += 1
            
            
def unblack(i,j,notpos,n):
    for ii in range(i,n):
        notpos[ii][j] -= 1
    for ii in range(j,n):
        if i + ii - j < n:
            notpos[i + ii - j][ii] -= 1
    for ii in range(j):
        if i + j - ii < n:
            notpos[i + j - ii][ii] -= 1            
        


def solve(level,pattern,notpos,ans,n):
    if level == n:
        ans.append(pattern)
        return 
    
    for i in range(n):
        if notpos[level][i] == 0:
            black(level,i,notpos,n)
            solve(level + 1,pattern + [i + 1],notpos,ans,n)
            unblack(level,i,notpos,n)
    


class Solution:
    def nQueen(self, n):
        notpos = [[0]*n for _ in range(n)]
        ans = []
        solve(0,[],notpos,ans,n)
        return ans 
            
0
namantyagi63375 days ago
EASY TO UNDERSTAND BACKTRACKING SOLUTION
 
class Solution{public:   bool is_safe(int row,int col,vector<vector<int>>& ch,int n)   {       for(int i=0;i<col;i++)       {           if(ch[row][i])               return false;       }       for(int i=row,j=col;i>=0 && j>=0;i--,j--)       {           if(ch[i][j])               return false;       }       for(int i=row,j=col;i<n && j>=0;i++,j--)       {           if(ch[i][j])               return false;       }       return true;   }   void solve(int col,int n,vector<vector<int>>& ch,vector<vector<int>>& fin_ans)   {       if(col==n)       {           vector<int> ans;           for(int i=0;i<n;i++)           {               for(int j=0;j<n;j++)               {                   if(ch[i][j]==1)                   {                       ans.push_back(j+1);                       break;                   }               }           }           fin_ans.push_back(ans);           return;       }       for(int i=0;i<n;i++)       {           if(is_safe(i,col,ch,n))           {               ch[i][col]=1;               solve(col+1,n,ch,fin_ans);               ch[i][col]=0;           }       }       return;   }   vector<vector<int>> nQueen(int n)    {       vector<vector<int>> ch(n,vector<int>(n,0));       int col=0;       vector<vector<int>> fin_ans;       solve(col,n,ch,fin_ans);       sort(fin_ans.begin(),fin_ans.end());       return fin_ans;   }}; 
+2
alekhyag06082 weeks ago
Java Solution
very easy to understand
With comments
class Solution{
    static ArrayList<ArrayList<Integer>> nQueen(int n) {
        // to store answer
        ArrayList<ArrayList<Integer>> ans=new ArrayList<>();
        boolean[][] board=new boolean[n][n];
        helper(board,ans,0);
        return ans;
        
    }
    private static void helper(boolean[][] board,ArrayList<ArrayList<Integer>> ans,int row){
        if(row==board.length){
            //a solution is found
            //add it to our list
            add(board,ans);
            return;
        }
        
        for(int col=0;col<board.length;col++){
            //checking whether the queen will be placed safely or not
            if(isSafe(board,row,col)){
                board[row][col]=true;
                helper(board,ans,row+1);
                //backtracking
                board[row][col]=false;
            }
        }
    }
    private static boolean isSafe(boolean[][] board,int row,int col){
        //check the above rows for queens
        for(int i=0;i<row;i++){
            if(board[i][col]){
                return false;
            }
        }
        //to check left diagonal
        int maxLeft=Math.min(row,col);
        for(int i=1;i<=maxLeft;i++){
            if(board[row-i][col-i]){
                return false;
            }
        }
        //to check right diagonal
        int maxRight=Math.min(row,board.length-col-1);
        for(int i=1;i<=maxRight;i++){
            if(board[row-i][col+i]){
                return false;
            }
        }
        return true;
    }
    
    private static void add(boolean[][] board,ArrayList<ArrayList<Integer>> ans){
        //this function adds solutions to the final answer
        ArrayList<Integer> sub=new ArrayList<Integer>();
        for(int row=0;row<board.length;row++){
            
            for(int col=0;col<board.length;col++){
                if(board[row][col]){
                    sub.add(col+1);
                }
            }
        }
        ans.add(sub);
    }
}

0
avinashsoni2 weeks ago
most optimal solution : 
 
class Solution{public:  int ld[30]={0};  int rd[30]={0};  int cr[30]={0};      bool f(vector<vector<int>>&ans , vector<vector<int>>&board , int col , int n){             if(col >= n){                vector<int>temp;                for(int i = 0 ; i < n ; ++i){                     for(int j = 0 ; j < n ; ++j){                           if(board[i][j] == 1) temp.push_back(j + 1);                     }                }                               ans.push_back(temp);                return true;           }                      bool flag = false;           for(int i = 0 ; i < n ; ++i){                                if(ld[i - col + n - 1 ]!=1 && rd[i + col]!=1 && cr[i]!=1){                                           board[i][col] = 1;                   ld[i - col + n - 1] = rd[i + col ] = cr[i] = 1;                                      flag  = f(ans , board , col + 1 , n) || flag;                                      board[i][col] = 0;                   ld[i - col + n - 1] = rd[i + col ] = cr[i] = 0;                                    }           }                      return flag;                      }     vector<vector<int>> nQueen(int n) {     vector<vector<int>>ans;     vector<vector<int>>board(n,vector<int>(n,0));          f(ans,board,0,n);     sort(ans.begin(),ans.end());     return ans;            }};
+1
ambuj60092 weeks ago
class Solution{public:   bool issafe(int r,int j, int n, vector<int> temp)   {       for(auto x:temp) //to check in col queen       {           if(x==j)               return false;       }       for(int i=0;i<temp.size();i++) //to check diag queen       {           if((r-i-1)==abs(j-temp[i]))               return false;       }       return true;   }   void solve(int r,int n, vector<int> &temp , vector<vector<int>> &ans)   {       if(r>n)//if ans is achieved       {           ans.push_back(temp);           return;       }       for(int c=1;c<=n;c++) //checking for all columns       {           if(issafe(r,c,n,temp)) //checking if curr position is safe           {               temp.push_back(c);               solve(r+1,n,temp,ans); //callin for forward positons               temp.pop_back(); //backtrack           }       }   }   vector<vector<int>> nQueen(int n) {       // code here       vector<vector<int>> ans;       vector<int> temp;       solve(1,n,temp,ans);       return ans;   }};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested 
                                    against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
                                    On submission, your code is tested against multiple test cases consisting of all
                                        possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
                                        the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested 
                                against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the 
                                correctness of code. On submission, your code is tested against multiple test cases
                                    consisting of all possible corner cases and stress constraints.