【wikioi】1295 N皇后问题

题目链接

算法:DFS

刚开始卡了我一下,我竟然傻到用二维来放皇后= =。导致一直TLE。。。。

其实用1维就行了的,下标为行(列),值为列(行)

我是用下标为列做的。

上代码

#include <iostream>

using namespace std;
int n, ans = 0;
int map[14];
void dfs(int x)
{
	if(x > n) {ans++; return;}
	int i, j;
	for(i = 1; i <= n; i++) //放在某行
	{
		map[x] = i;
		for(j = 1; j < x; j++) //判断前面列是否有重合,直接判断横行 和 斜行 (可自己画图为什么判断斜行成立)
			if((map[j] == map[x]) ||
			   (x-map[x] == j-map[j] || x+map[x] == j+map[j]))
				break;
		if(j == x)
			dfs(x+1);
	}
}

int main()
{
	cin >> n;
	dfs(1);
	cout << ans;
	return 0;
}
原文地址:https://www.cnblogs.com/iwtwiioi/p/3521815.html