# N Queens

Posted: 24 Sep, 2020

Difficulty: Hard

#### You are given an integer 'N'. For a given 'N' x 'N' chessboard, find a way to place 'N' queens such that no queen can attack any other queen on the chessboard.

#### A queen can be killed when it lies in the same row, or same column, or the same diagonal of any of the other queens. You have to print all such configurations.

##### Input Format:

```
The first and the only line of input contains an integer 'N' representing the size of the chessboard and the number of queens.
```

##### Output Format:

```
Each line would be representing a single configuration.
Each configuration would contain 'N '* 'N' elements printed row-wise separated by spaces. The position where we can place the queen will have the value 1 rest will have the value 0.
```

##### Note:

```
You do not need to print anything, it has already been taken care of. Just implement the given function.
```

##### Constraints:

```
1 <= 'N' <= 10
Time Limit: 1sec
```

Approach 1

- Instead of checking all the places on the chessboard, we can use backtracking and place queen row-wise or column-wise.
- Suppose we place queens row-wise, and we start with the very first row. Place the queen and move to the next row until either there is a solution or there are no viable cells left.
- As we backtrack, check to place the queen in the different columns of the same row.
- When we can place a queen at the ‘N’th row, it means we have successfully placed all the ‘N’ queens so add this configuration to our final answer vector.
- At last, we will return the vector containing all the configurations in which we can successfully place the ‘N’ queens.

Approach 2

- So instead of using a 2-D array to depict the chessboard, We can use three linear/boolean arrays of ‘N’ size and it will decrease the cost to check the cell is safe or not from O(N) to O(1) as well as our space complexity will get reduced.
- For a queen to be safe in a cell, it should be safe in its row, column, upper right diagonal and upper-left diagonal.
- For checking columns, if a queen is present in a column, set that index as column number in the array.
- For checking upper left diagonal and upper right diagonal, try finding a pattern between the index of row and column.
- Upper left diagonal has a difference of row and column as constant.

Similarly, the upper right diagonal has a sum of row and column as constant. - So to check for diagonal we will match that particular constant(difference for upper left and sum for upper right), if that constant as the index is set for that specific array, that means the queen is present in diagonal, and that cell is not safe.
- When we can place a queen at the Nth row, it means we have successfully placed all the N queens so add this configuration to our final answer vector.
- At last, we will return the vector containing all the configuration in which we can successfully place the 'N' queens.