【LeetCode】51. N-Queens

来源:互联网 发布:mars渲染软件 编辑:程序博客网 时间:2024/06/13 07:57

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.

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<vector<string>>result;
bool check(int row,int col, int n,vector<string>m)
{
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(vector<string>m)
{
result.push_back(m);
}
void solve(int row,int n,vector<string>m)
{
int col;
if (row == n )//所有行已经全部放置
{
add(m);
return;
}
for (col = 0; col<n; col++)
{
if (check(row, col,n,m) == true)
{
m[row][col] = 'Q';
solve(row + 1,n,m);
m[row][col] = '.';
}
}
}
public:
vector<vector<string>> solveNQueens(int n) {
vector<string>m(n,string(n,'.'));//Init
solve(0, n,m);
return result;
}
};