LeetCode | 51. N-Queens 回溯法

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


Givenan integer n, return all distinct solutions tothe n-queens puzzle.

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

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

[

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

  "...Q",

  "Q...",

  "..Q."],

 

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

  "Q...",

  "...Q",

  ".Q.."]

]

还是n皇后问题,不过这一题要求输出所有的可能的结果,以矩阵的形式输出结果,所以这一题除了需要一个储存选择的数组以外,还需要一个存储最终结果的数组,

同样,这一题也有简单解法,使用一个solution数组,存储同斜线的可能发生非法的皇后位置的和和位置的差,这样能够省去判断斜线是否能够互相攻击的函数,这样能够提升算法的效率

以后在做递归的题目的时候要注意,在进入下一层递归的时候可能会修改一些设置,当递归返回的时候需要还原这些设置,这里需要注意的是这些设置的返回需要按照顺序返回,在进入下一层递归是按照怎样的顺序设置,在递归返回的时候就需要按照怎样的顺序还原!

class Solution {
public:
void p(vector<vector<string>> &result,vector<bool> &solution,vector<string> &mark, vector<int> &select,int t,int n)
{
	if (t == n)
	{
		result.push_back(mark);
	}
	for (int i = t; i < n; i++)
	{
		if (solution[3*n+t - select[i]] && solution[t + select[i]])
		{
			solution[3 * n + t - select[i]] = false;
			solution[t + select[i]] = false;
			swap(select[t], select[i]);
			mark[t][select[t]] = 'Q';
			p(result,solution, mark, select, t + 1, n);
			mark[t][select[t]] = '.';
			swap(select[t], select[i]);
			solution[t + select[i]] = true;
			solution[3 * n + t - select[i]] = true;
		}
	}

}
vector<vector<string>> solveNQueens(int n) {
	vector<vector<string>> result;
	vector<bool> solution(4 * n, true);
	vector<string> mark;
	vector<int> select;
	string u;
	u.insert(0, n, '.');
	for (int i = 0; i < n; select.push_back(i), i++, mark.push_back(u));
	p(result, solution, mark, select, 0, n);
	return result;
}
};


    

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值