51. N-Queens, leetcode

本文介绍了一种使用回溯算法解决N皇后问题的方法,并提供了两种实现思路:递归方法和栈方法。通过实例展示了如何找到所有不冲突的解,特别针对4皇后问题给出了具体解答。

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

题目:

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.

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

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

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

代码及思路:(回溯的递归方法)15ms AC

class Solution {
public:
	int place(int k)//k 表示行数;函数的意思是,查看(k,x[k])是否可以放皇后
	{
		for (int i = 0; i < k ; i++)//当前行是k - 1
			if (abs(k - i) == abs(x[k] - x[i]) || x[i] == x[k]) return 0;
		return 1;
	}
	void Backtrak(int t)
	{
		if (t > n - 1)
		{
			sum++;
			vector<string> temp;
			string a(n,'.');
			for(auto p : x)
			{
			    a[p] = 'Q';
			    temp.push_back(a);
			    a[p] = '.';
			}
			ans.push_back(temp);
			
		}
		else
		{
			for (int i = 0; i < n; i++)
			{
				x[t] = i;
				if (place(t))
					Backtrak(t + 1);
			}
			
		}
	}
	vector<vector<string>> solveNQueens(int in) {
		vector<int> vec(in, -1);
		x = vec;
		n = in;
		
		Backtrak(0);
		
		
		return ans;

	}
private:
	vector<int> x;//注意1:这里不能写作vector<int> x(); 否则认为x是一个函数;并且在这里对x进行初始化也将报错。
	int n;//注意2:这里n是可以初始化的
	int sum = 0;
	vector<vector<string>> ans;
};

代码及思路2:(回溯的栈方法)

待续

总结:

1,对于回溯问题,最好找一个数据结构存储解的集合。比如这里的x[i],表示第i行的第j列可以放皇后。即用
数组存储每行皇后的位置
2,其中一个微小笔误,浪费了好长时间去排查。为什么用这么长时间才排查出来,是因为排查方法不当,
所以以后写代码出现错误,不要害怕,打开IDE设置合适的断点,很容易就可以找出来的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值