【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;
}
};
- LeetCode 51. N-Queens
- LeetCode --- 51. N-Queens
- LeetCode 51.N-Queens
- [Leetcode] 51. N-Queens
- [leetcode] 51.N-Queens
- [leetcode] 51. N-Queens
- LeetCode 51. N-Queens
- leetcode 51. N-Queens
- 【LeetCode】51. N-Queens
- leetcode 51. N-Queens
- LeetCode 51. N-Queens
- LeetCode 51. N-Queens
- leetcode.51. N-Queens
- Leetcode 51. N-Queens
- LeetCode 51. N-Queens
- [LeetCode] 51. N-Queens
- leetcode 51. N-Queens
- leetcode-51. N-Queens
- Keras中文文档
- QRegExp 正则表达式详解
- 报错修改:Tomcat version 7.0 only supports J2EE 1.2, 1.3, 1.4, and Java EE 5 and 6 Web
- react-native新导航组件react-navigation详解
- android:descendantFocusability用法简析
- 【LeetCode】51. N-Queens
- 图片浏览
- 淘宝登录
- 深度学习边缘提取HED(Holistically-Nested Edge Detection) c++接口实现
- 设计模式---解释器模式
- 【数学思维】CodeForces
- kepServerEx远程连接问题记录
- 搭建weex开发环境
- spacy en_core_web_md下载安装及使用