Algorithm medium | 33. N queen problem

Keywords: Java Python

Title Description

N queen problem is to place n queens on n*n chessboard. Queens can't attack each other (any two Queens can't be in the same row, same column, same diagonal).

Given an integer n, returns the solution to all the different N Queens problems.

Each solution contains a clear n queen placement layout, where "Q" and "." represent a queen and an empty location, respectively.

Example 1

```Input: 1
Output:
[["Q"]]
```

Example 2

```Input: 4
Output:
[
// Solution 1
[".Q..",
"...Q",
"Q...",
"..Q."
],
// Solution 2
["..Q.",
"Q...",
"...Q",
".Q.."
]
]
```

java solution

```class Solution {
List<List<String>> solveNQueens(int n) {
List<List<String>> results = new ArrayList<>();
if (n <= 0) {
return results;
}

search(results, new ArrayList<Integer>(), n);
return results;
}

/*
* results store all of the chessboards
* cols store the column indices for each row
*/
private void search(List<List<String>> results,
List<Integer> cols,
int n) {
if (cols.size() == n) {
return;
}

for (int colIndex = 0; colIndex < n; colIndex++) {
if (!isValid(cols, colIndex)) {
continue;
}
search(results, cols, n);
cols.remove(cols.size() - 1);
}
}

private List<String> drawChessboard(List<Integer> cols) {
List<String> chessboard = new ArrayList<>();
for (int i = 0; i < cols.size(); i++) {
StringBuilder sb = new StringBuilder();
for (int j = 0; j < cols.size(); j++) {
sb.append(j == cols.get(i) ? 'Q' : '.');
}
}
return chessboard;
}

private boolean isValid(List<Integer> cols, int column) {
int row = cols.size();
for (int rowIndex = 0; rowIndex < cols.size(); rowIndex++) {
if (cols.get(rowIndex) == column) {
return false;
}
if (rowIndex + cols.get(rowIndex) == row + column) {
return false;
}
if (rowIndex - cols.get(rowIndex) == row - column) {
return false;
}
}
return true;
}
}
```

C++ solution

```class Solution {
public:
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > result;
if( n <= 0 )
{
return result;
}
vector<int> cols;
search(n, cols, result);
return result;
}

void search(int n, vector<int> &cols, vector<vector<string> > &result)
{
if(cols.size() == n)
{
result.push_back(drawResult(cols, n));
return;
}
for(int col = 0; col < n; col++)
{
if(!isValid(cols, col))
{
continue;
}
cols.push_back(col);
search(n, cols, result);
cols.pop_back();
}
}
bool isValid(vector<int> &cols, int col)
{
int row = cols.size();
for(int i = 0; i < row; ++i)
{
if(cols[i] == col)
{
return false;
}
if(i - cols[i] == row - col)
{
return false;
}
if(i + cols[i] == row + col)
{
return false;
}
}
return true;
}

vector<string> drawResult(vector<int> &cols, int n)
{
vector<string> result;
for(int i = 0; i < cols.size(); ++i)
{
string temp(n, '.');
temp[cols[i]] = 'Q';
result.push_back(temp);
}
return result;
}
};
```

python solution

It is a depth first search algorithm with permutation.

```class Solution:
def solveNQueens(self, n):
results = []
self.search(n, [], results)
return results

def search(self, n, cols, results):
row = len(cols)
if row == n:
results.append(self.draw_chessboard(cols))
return

for col in range(n):
if not self.is_valid(cols, row, col):
continue
cols.append(col)
self.search(n, cols, results)
cols.pop()

def draw_chessboard(self, cols):
n = len(cols)
board = []
for i in range(n):
row = ['Q' if j == cols[i] else '.' for j in range(n)]
board.append(''.join(row))
return board

def is_valid(self, cols, row, col):
for r, c in enumerate(cols):
if c == col:
return False
if r - c == row - col or r + c == row + col:
return False
return True
```
152 original articles published, 20 praised, 5314 visited

Posted by lazzerous on Sun, 26 Jan 2020 07:17:48 -0800