Leetcode: N-Queens

本文介绍了一种解决N皇后问题的方法,通过排列组合的方式寻找所有可能的棋盘配置方案,确保任意两个皇后都不会互相攻击。文章详细展示了如何利用递归算法进行全排列,并检查每个排列是否符合N皇后问题的要求。

摘要生成于 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.."]
]

vector<int> nums(n);num[i]表示第i行的queen放在num[i]列,这样就转化成求0-n-1的全排列,然后看每一个排列是否符合条件。

vector<vector<string>> res;
	void permutationHelper(vector<int> &nums, int index, int n)
	{
		if(index == n)
		{
			bool flag = true;
			for(int i = 0; i<n && flag; i++)
				for(int j=i+1; j<n; j++)
					if((j-i) == abs(nums[j]-nums[i]))
					{
						flag = false;
						break;
					}

			if(flag)
			{
				vector<string> tmp;
				for(int i =0; i<n;i++)
				{
					string row(n,'.');
					row[nums[i]]='Q';
					tmp.push_back(row);
				}
				res.push_back(tmp);
			}
		}
		for(int i = index; i < n; i++)
		{
			swap(nums[index], nums[i]);
			permutationHelper(nums, index+1, n);
			swap(nums[index], nums[i]);
		}
	}
	void permutation(int n)
	{
		vector<int> nums(n);
		for(int i = 0; i < n; i++)
			nums[i] = i;
		permutationHelper(nums,0,n);
	}
	vector<vector<string> > solveNQueens(int n) {
        // Note: The Solution object is instantiated only once.
        res.clear();
		permutation(n);
		return res;
    }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值