【LeetCode】51. N-Queens

Description:

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

【LeetCode】51. N-Queens_第1张图片

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

Example:

There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

题目思考:

这道题是经典的N皇后问题,NP问题,主要思路是采用递归不断处理子问题。

放置n的皇后在n*n的棋盘上,使其任意两个皇后不能相互攻击。给定整数n,返回所有可能情况,其中‘Q’表示皇后,‘.’表示空位置。

两个皇后不能相互攻击,即要求这两个皇后不在同一行、同一列及同一斜线上。


 Solution:

class Solution {
private:
vector>result;
bool check(int row,int col, int n,vectorm)
{
if (row == 0)
return true;
int i;
int j;
for (i = 0; i < row; i++)
{
if (m[i][col] == 'Q')
return false;
}
i = row - 1;
j = col - 1;
while (i >= 0 && j >= 0)
{
if (m[i][j] == 'Q')
return false;
i--;
j--;
}
i = row - 1;
j = col + 1;
while (i >= 0 && j < n)
{
if (m[i][j] == 'Q')
return false;
i--;
j++;
}
return true;
}
void add(vectorm)
{
result.push_back(m);
}
void solve(int row,int n,vectorm)
{
int col;
if (row == n )//所有行已经全部放置
{
add(m);
return;
}
for (col = 0; col{
if (check(row, col,n,m) == true)
{
m[row][col] = 'Q';
solve(row + 1,n,m);
m[row][col] = '.';
}
}
}
public:
vector> solveNQueens(int n) {
vectorm(n,string(n,'.'));//Init
solve(0, n,m);
return result;
}
};


你可能感兴趣的:(【LeetCode】51. N-Queens)