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
kinshukjagdev3 days ago
class Solution{public:   void convert(vector<vector<int>>& ans, vector<vector<int>>& board, int n){       vector<int> temp;       for(int i=0; i<n; i++){           for(int j=0; j<n; j++){               if(board[j][i]==1)                   temp.push_back(j+1);           }       }       ans.push_back(temp);   }   bool isSafe(int row, int col, vector<vector<int>> &board, int n){       int x = row;       int y = col;       while(y>=0){           if(board[x][y]==1)               return 0;           y--;       }       x = row;       y = col;       while(y>=0&&x>=0){           if(board[x][y]==1)               return 0;           y--;           x--;       }       x = row;       y = col;       while(y>=0&&x<n){           if(board[x][y]==1)               return 0;           y--;           x++;       }       return 1;   }   void solve(int col, vector<vector<int>> &ans,                vector<vector<int>>& board, int n)   {       if(col==n){           convert(ans, board, n);           return;       }       for(int row=0; row<n; row++){           if(isSafe(row, col, board, n))           {               board[row][col] = 1;               solve(col+1, ans, board, n);               board[row][col] = 0;           }       }   }   vector<vector<int>> nQueen(int n) {       // code here       vector<vector<int>> ans;       vector<vector<int>> board(n, vector<int>(n, 0));       solve(0, ans, board, n);       return ans;   }};
-1
linhnvhan1 week ago
    bool isValid (vector<int> result, int row, int col) {       for (int i = 0; i < row; ++i) {           if (result[i] == col)               return false;       }       // same diagonal       for (int i = 0; i < row; ++i) {           if (col == result[i] - (row - i) || col == result[i] + (row - i))               return false;       }       return true;   }   void solveNQueen (vector<vector<int>> &results, vector<int> &result, int row, int n) {       if (row == n){           results.push_back (result);           return;       }       for (int i = 0; i < n; ++i) {           result.push_back (i + 1);           if (isValid (result, row, i + 1)){               solveNQueen (results, result, row + 1,n);           }           result.pop_back();       }   }   vector<vector<int>> nQueen(int n) {       // code here       vector<int> result;       vector<vector<int>> results;       solveNQueen (results, result, 0, n);       return results;   }
0
tarundhiman851 week ago
JAVA  0.34/2
 
class Solution{        private static void solve(int col, char[][] board, ArrayList<ArrayList<Integer>> res, int[] leftRow, int[] lowerDiagonal, int[] upperDiagonal){       if(col==board.length){           res.add(construct(board));           return;       }       for(int row = 0; row<board.length; row++){           if(leftRow[row]==0 && lowerDiagonal[row+col]==0 && upperDiagonal[board.length-1+col-row]==0){               board[row][col]='Q';               leftRow[row] = 1;               lowerDiagonal[row+col] = 1;               upperDiagonal[board.length-1+col-row]=1;               solve(col+1, board, res, leftRow, lowerDiagonal, upperDiagonal);               //reset to normal               board[row][col] = '.';               leftRow[row] = 0;               lowerDiagonal[row+col] = 0;               upperDiagonal[board.length - 1 + col -row] = 0;           }       }   }   private static ArrayList<Integer> construct(char[][] board){       ArrayList<Integer> res = new ArrayList<>();       for(int i=0; i<board.length; i++)       {           for (int j = 0; j < board[0].length; j++) {               if(board[i][j]=='Q') res.add(j+1);           }       }       return res;   }   static ArrayList<ArrayList<Integer>> nQueen(int n) {       // code here       char[][] board = new char[n][n];       for(int i=0; i<n; i++){           for(int j=0; j<n; j++){               board[i][j]='.';           }       }       ArrayList<ArrayList<Integer>> res = new ArrayList<>();       int [] leftRow = new int[n];       int [] upperDiagonal = new int[2*n-1];       int [] lowerDiagonal = new int[2*n-1];       solve(0, board, res, leftRow, lowerDiagonal, upperDiagonal);   Collections.sort(res, new Comparator<ArrayList<Integer>>() {           @Override           public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {               if(o1.size()==o2.size()){                   for(int i=0; i<o1.size(); i++){                       if(o1.get(i)>o2.get(i)) return 1;                       else if(o1.get(i)<o2.get(i)) return -1;                   }               }               else if(o1.size()>o2.size()) return 1;               else return -1;                           return 0;           }       });       return res;   }   }
0
dev1713 weeks ago
SIMPLE C++ BACKTRACKING 
bool isValid(int row,int col,int n,vector<vector<int>>&vis){
 			// up  
      int i=row-1,j=col-1;
    for(;i>=0 && j>=0;i--,j--){
        if(vis[i][j]==1)
        return false;
    }
    //top left
    i=row-1;
    for(;i>=0;i--){
        if(vis[i][col]==1)
        return false;
    }
    // top right
    i=row-1,j=col+1;
    for(;i>=0 && j<n ;i--,j++){
        if(vis[i][j]==1)
        return false;
    }
    return true;
}
void solve(int row,int n,vector<vector<int>>&ans,vector<vector<int>>&vis,vector<int>&temp){
    if(row==n){
        ans.push_back(temp);
        return;
    }
    for(int col=0;col<n;col++){
        if(isValid(row,col,n,vis)){
            vis[row][col]=1;
            temp[col]=row+1;
            solve(row+1,n,ans,vis,temp);
            vis[row][col]=0;
             temp[col]=-1;
        }
    }
}
    vector<vector<int>> nQueen(int n) {
        // code here
        vector<vector<int>>ans,vis(n,vector<int>(n,0));
        vector<int>temp(n,-1);
        solve(0,n,ans,vis,temp);
        sort(ans.begin(),ans.end());
        return ans;
        
    }
0
sunboykenneth3 weeks ago
With O(n) space:
 
class Solution{
private:
    bool isValidPlacement(int curRow, int curCol, const vector<int> &placedQueen) {
        // Same row ?
        for (int i = 0; i < curCol; i++) {
            if (curRow == placedQueen[i]) {
                return false;
            }
        }
        
        // Same diag
        for (int i = 0; i < curCol; i++) {
            if (curCol - i == abs(curRow - placedQueen[i])) {
                return false;
            }
        }
        
        return true;
    }
    
    
    void nQueenImpl (int n, int curCol, vector<int> &placedQueen, vector<vector<int>>& resultArr) {
        if (curCol == n) {
            resultArr.push_back(placedQueen);
            return;
        }
        
        for (int curRow = 0; curRow < n; curRow++) {
            if (!isValidPlacement(curRow, curCol, placedQueen)) {
                continue;
            }
            
            placedQueen[curCol] = curRow;
            nQueenImpl(n, curCol + 1, placedQueen, resultArr);
        }
    }
    
    
public:
    vector<vector<int>> nQueen(int n) {
        if (n == 0) {
            return {};
        }
        
        vector<int> placedQueen = vector<int>(n, -1);
        vector<vector<int>> resultArr;
        
        nQueenImpl(n, 0, placedQueen, resultArr);
        
        for (int i = 0; i < resultArr.size(); i++) {
            for (int j = 0; j < resultArr[i].size(); j++) {
                resultArr[i][j]++;
            }
        }
        
        return resultArr;
    }
};
+1
adityagagtiwari4 weeks ago
Java ez solution . If you find this helpful please upvoteclass Solution{   static ArrayList<ArrayList<Integer>> nQueen(int n) {       // code here        ArrayList<ArrayList<Integer>> result = new ArrayList<>();        int[][] arr = new int[n][n];        nQueens(arr,0,result,n);          return result;   }   static void nQueens(int[][] arr,int row,ArrayList<ArrayList<Integer>> result,int n)   {       if(row==arr.length)       {           //collect answers and reinitialize a to remove the current answer            ArrayList<Integer> answer = new ArrayList<>();           for(int i=0;i<arr.length;i++)           {               for(int j=0;j<arr.length;j++)               {                   if(arr[i][j]==1)                   answer.add(j+1);               }           }           result.add(answer);          arr = new int[n][n];          return;       }              for(int col=0;col<n;col++)       {           if(isSafe(arr,row,col))           {               arr[row][col] = 1;               nQueens(arr,row+1,result,n);               arr[row][col] = 0;           }       }   }   public static boolean isSafe(int[][] arr,int row,int col)   {       //check up        for(int i = row-1 ; i>=0 ; i--)         {             if(arr[i][col]==1)             return false;         }        //check diagonals        for(int i=row-1,j=col-1;i>=0 && j>=0 ; j--,i--)       {             if(arr[i][j]==1)             return false;       }         for(int i=row-1,j=col+1;i>=0 && j<arr[0].length ; j++,i--)       {             if(arr[i][j]==1)             return false;       }       return true;   }}
0
amritanshusingh31 month ago
Within time constraints 
WITHOUT using EXTRA SPACE for VISITED MATRIX or VECTORS.
Calculating safe diagonals and columns using values already picked up in result vector
class Solution{
public:
	vector<vector<int>> ans; // global answer 2-D vector
	bool isSafe(int row, int col, vector<int> &path)
	{
		for (int i = row - 2; i >= 0; i--) 
		// to check horizontally
		{
			if (path[i] == col)
				return false;
		}
		for (int i = row - 2; i >= 0; i--) 
		// to check diag left_inclined
		{
			if(path[i] == i - row + col + 1)
			return false;
		}
		for (int i = row - 2; i >= 0; i--) 
		// to check diag right_inclined
		{
			if(path[i] == row + col - i - 1)
			return false;
		}
		return true;
	}

	void helper(int row, int n, vector<int> path)
	{
		if (path.size() == n) // base case
		{
			ans.push_back(path);
		}

		for (int col = 1; col <= n; col++)
		{
			if (isSafe(row, col, path))
			{
				path.push_back(col);
				helper(row + 1, n, path);
				path.pop_back();
			}
		}
	}

	vector<vector<int>> nQueen(int n)
	{
		if (n == 0 || n == 2 || n == 3)
			return ans; //return empty 2d vector
		if (n == 1)
			return {{1}};
		vector<int> path;
		helper(1, n, path);
		return ans;
	}
};

 
+1
gulashanshashishekhar291 month ago
Time Complexity = O(n!) ; Run Time = 0.1  
Space Complexity = O(n2)
class StateSpace {
    vector<vector<bool>> grid;
public:
    vector<int> position;
    StateSpace(int n) {
    grid = vector<vector<bool>>(n, vector<bool>(n, false));
    position = vector<int>(n, 0);
    }
        
    bool isSafe(int i, int j, const int n) {
        if (i < 0 || i >= n || j < 0 || j >= n) return true;
        return !grid[i][j];
    }
        
    void place(int i, int j) {
        grid[i][j] = true;
        position[i] = j+1;
    }
       
    void unplace(int i, int j) {
        grid[i][j] = false;
        position[i] = 0;
    }
};
    
bool safe(int i, int j, const int n, StateSpace &s) {
    for (int k = 0; k < i ; k++) {
        if (!s.isSafe(i-k-1, j, n)     ||
            !s.isSafe(i-k-1, j-k-1, n) ||
            !s.isSafe(i-k-1, j+k+1, n)) return false;
    }
    return true;
} 
    
void placeQueen(int i, const int n, StateSpace &s, vector<vector<int>> &result) {
    if (i == n) {
        result.push_back(s.position);
        return;
    }

    for (int j = 0; j < n; j++) {
        if (!safe(i, j, n, s)) continue;
        s.place(i, j);
        placeQueen(i+1, n, s, result);
        s.unplace(i, j);
    }
}    

public:    
    vector<vector<int>> nQueen(int n) {
        // code here
        StateSpace s(n);
        vector<vector<int>> result;
        placeQueen(0, n, s, result);
        return result;
}
-1
rahul72parihar2 months ago
C++  Bhai ye solution le jao or mast code chalao
 
void solve(vector<bool> &lowerDiagonal, vector<bool> &upperDiagonal, vector<bool> & sideRow,   int col, int n, vector<vector<int>> &ans, vector<int> &temp){       if(col== n){           ans.push_back(temp);           return;       }       for(int i = 0; i<n; i++){           if(sideRow[i]==true|| lowerDiagonal[col+i]==true)continue;           if(upperDiagonal[n-1+col-i]==true)continue;           sideRow[i]=true;           lowerDiagonal[col+i]=true;           upperDiagonal[n-1+col-i]= true;           temp.push_back(i+1);           solve(lowerDiagonal, upperDiagonal, sideRow, col+1, n, ans, temp);           temp.pop_back();           upperDiagonal[n-1+col-i]=false;           lowerDiagonal[col+i]=false;           sideRow[i]=false;       }       return;   }      vector<vector<int>> nQueen(int n) {       vector<bool> lowerDiagonal(n*2-1, false);       vector<bool> upperDiagonal(n*2-1, false);       vector<bool> sideRow(n, false);       vector<vector<int>> ans;       vector<int> temp;       solve(lowerDiagonal, upperDiagonal, sideRow, 0, n, ans, temp);       return ans;   }
0
parikhsharan62 months ago
// Java solution, 0.4s
 
class Solution {   static ArrayList<ArrayList<Integer>> nQueen(int n) {
       ArrayList<ArrayList<Integer>> answer = new ArrayList<>(new ArrayList<>());       helper(n, new ArrayList<>(), 0, answer);       return answer;   }      private static void helper(int n, ArrayList<Integer> currConfig, int i, ArrayList<ArrayList<Integer>> configs) {              if(currConfig.size() == n) {           configs.add(new ArrayList<>(currConfig));           return;       }              if(i >= n) {           return;       }              for(int j = 0; j < n; j++) {           if(isAttackPossible(currConfig, i, j, n)) {               continue;           }           currConfig.add(j + 1);           helper(n, currConfig, i + 1, configs);           currConfig.remove(currConfig.size() - 1);       }   }      private static boolean isAttackPossible(ArrayList<Integer> config, int i, int j, int n) {              boolean temp = false;              for(int k = 0; k < config.size(); k++) {           if(j == (config.get(k) - 1) || Math.abs(k - i) == Math.abs(config.get(k) - 1 - j)) {               temp = true;               break;           }       }              return temp;   }}
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.