leetcode51.N皇后

链接:

https://leetcode-cn.com/problems/n-queens/

描述:

在这里插入图片描述

示例:

在这里插入图片描述
在这里插入图片描述

代码:

class Solution {
public:
	vector<vector<string>> solveNQueens(int n) {
		//按坐标位置存放所有解决方案
		vector<vector<pair<int, int>>> solutions;
		//存放一种解决方案中的所有皇后的位置
		vector<pair<int, int>> solution;
		DFS(solutions, solution, 0, n);
		//把坐标位置转成string
		return transResult(solutions, n);
	}
	void DFS(vector<vector<pair<int, int>>>& solutions, vector<pair<int, int>>& solution, int curRow, int n)
	{
		if (curRow == n) solutions.push_back(solution);
		//尝试当前行的每一个位置是否可以放置一个皇后
		for (int col = 0; col < n; ++col) {
			if (isValid(solution, curRow, col)) {
				//如果可以,在保存当前位置,继续确定下一行皇后的位置
				//直接调用构造函数,内部构造pair, 或者调用make_pair
				solution.emplace_back(curRow, col);
				DFS(solutions, solution, curRow + 1, n);
				//回溯,删除当前位置,尝试当前行的其它位置
				solution.pop_back();
			}
		}
	}
	// solution: 一个解决方案,从第一行开始到当前行的上一行每一行已经放置皇后的点
	bool isValid(vector<pair<int, int>>& solution, int row, int col) {
		// 判断当前行尝试的皇后位置是否和前面几行的皇后位置有冲突
		// i.second == col: 第i个皇后与当前这个点在同一列
		// i.first + i.second == row + col: 第i个皇后与当前点在撇上,横坐标+纵坐标值相同
		// i.first - i.second == row - col:第i个皇后与当前点在捺上, 横坐标-纵坐标值相同
		for (pair<int, int>& i : solution)
			if (i.second == col || i.first + i.second == row + col
				|| i.first - i.second == row - col)
				return false;
		return true;
	}
	vector<vector<string>> transResult(vector<vector<pair<int, int>>>& solutions, int n) {
		vector<string> tmp();
		//把每一种解决方案都转换为string形式,最终结果
		vector<vector<string>> ret;
		for (vector<pair<int, int>>& solution : solutions) {
			//n*n char: 每行有n个元素,把皇后的位置修改为Q
			vector<string> solutionString(n, string(n, '.'));
			for (pair<int, int>& i : solution) {
				solutionString[i.first][i.second] = 'Q';
			}
			ret.push_back(solutionString);
		}
		return ret;
	}
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值