【Leetcode】51. N-Queens (搜索)

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.

Example:

Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

题目大意:

每个Q周围的八个格子中不允许出现Q。

解题思路:

按行搜索,所以我们只需要考虑每一列是否存在或者斜线上是否存在,所以我们可以看出搜索的判断条件有两个,1)当前Q的列号是否前面出现过。2)当前Q的列号与之前Q的列号相减的绝对值如果等于行号的差,则两个位于同一条斜线上。

 开始学习C++,以后Python和C++混合双打。

#include <vector>
#include <string>
#include <cstdio>
#include <iostream>
#include <stdlib.h>
using namespace std;

class Solution {

private:
	vector<string> board;
	vector<vector<string>> ans;

	void solve(vector<string>& board, vector<int>& pos, int num, int n) {
		if (num == n) {
			ans.push_back(board);
			return;
		}
		for (int i = 0; i < n; i++) {
			pos[num] = i;
			if (valid(pos, num)) {
				board[num][i] = 'Q';
				solve(board, pos, num + 1, n);
				board[num][i] = '.';
			}
		}

	}

	bool valid(vector<int>& pos, int num) {
		for (int i = 0; i < num; i++) {
			if (pos[i] == pos[num] || abs(pos[i] - pos[num]) == num - i) {
				return false;
			}
		}
		return true;
	}

public:
	vector<vector<string>> solveNQueens(int n) {
		string row(n, '.');
		for (int i = 0; i < n; i++) {
			board.push_back(row);
		}
		vector<int> pos = vector<int>(n);
		// 此处不跑图,只跑N个位置,查找是否存在有横纵坐标相同的情况
		solve(board, pos, 0, n);

		return ans;
	}
};

int main(void) {
	Solution obj;
	vector<vector<string>> ans;
	ans = obj.solveNQueens(4);
	for (int i = 0; i < ans.size(); i++) {
		for (int j = 0; j < ans[i].size(); j++) {
			cout << ans[i][j] << endl;
		}
		cout << '\n';
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值