[LeetCode] N-Queens

本文介绍了一种解决N皇后问题的有效算法。通过递归搜索和冲突检查的方式,在N×N的棋盘上放置N个皇后,确保任意两个皇后都不会互相攻击。文章提供了具体的代码实现,展示了如何找到所有可能的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

[Problem]

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] N-Queens - coder007 - Coder007的博客

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.

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

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

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

[Solution]

class Solution {
public:
// is the new Queen valid
bool valid(int row, int column, vector<pair<int, int> > &located){
for(int i = 0; i < located.size(); ++i){
if(located[i].first + located[i].second == row + column || located[i].second - located[i].first == column - row){
return false;
}
}
return true;
}

// search location
vector<vector<string> > search(bool column[], int n, int mth, vector<pair<int, int> > &located){
vector<vector<string> > res;

// the last row
if(mth == n - 1){
for(int i = 0; i < n; ++i){
if(column[i] == false && valid(mth, i, located)){
string str(n, '.');
str[i] = 'Q';

// add result
vector<string> tmp;
tmp.push_back(str);
res.push_back(tmp);
}
}
}
else{
for(int i = 0; i < n; ++i){
// valid in the ith column
if(column[i] == false && valid(mth, i, located)){

// locate a Queen in (mth, i)
column[i] = true;
located.push_back(make_pair(mth, i));
string str(n, '.');
str[i] = 'Q';

// search in the next row
vector<vector<string> > r = search(column, n, mth+1, located);
for(int j = 0; j < r.size(); ++j){
r[j].insert(r[j].begin(), str);
res.push_back(r[j]);
}

// back
column[i] = false;
located.pop_back();
}
}
}
return res;
}

// n queen
vector<vector<string> > solveNQueens(int n) {
// Start typing your C/C++ solution below
// DO NOT write int main() function

// the columns with Queen
bool column[n];
memset(column, false, sizeof(column));

// located Queens
vector<pair<int, int> > located;

// search
return search(column, n, 0, located);
}
};


 说明:版权所有,转载请注明出处。 Coder007的博客
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值