Q9.9 N queens

Q: Write an algorithm to print all ways of arranging eight queens on a chess board so that none of them share the same row, column or diagonal.

A: 经典的8皇后问题。DFS

#include 
#include 
#include 
using namespace std;

void dfs(vector &colum, vector &main_diag, vector &anti_diag, int row, vector > &res, vector &path) {
	const int N = path.size();
	if (row == N) {
		vector cur;
		for (int i = 0; i < N; i++) {
			string s(N,'.');
			s[path[i]] = 'Q';
			cur.push_back(s);
			cout< > n_queen(const int n) {
	vector colum(n, 0);
	vector main_diag(2*n, 0);
	vector anti_diag(2*n, 0);
	vector > res;
	vector path(n, 0);
	dfs(colum, main_diag, anti_diag, 0, res, path);
	return res;
}

int main() {
	n_queen(8);
	return 0;
}


你可能感兴趣的:(Cracking,the,coding,interview)