八皇后问题及其优化
每次遍历一个节点,看这个节点是否已经被遍历过或者这个列或者行或者两个对角线已经被遍历过,如果遍历过,就直接返回,如果没有被遍历过,就将该节点处的字符改为Q,将该行的数组置1,该列的数组置1,两个对角线的数组置1,然后继续遍历下一个相邻的节点,直到所有的节点都被遍历完,如果矩阵被遍历完,返回的时候,将该节点重新返回到初始化的时候,将该行的数组,该列的数组,两个对角线的数组重新置0,继续下一个节点,继续将这个节点改为Q,然后,继续遍历其他点,直到每层节点都被枚举到为止。
优化:位运算八皇后
(1)时间复杂度:O(n*n)
(2)解题思路:将函数中的参数改成遍历到的节点的行row、左列ld和右列rd,row|ld|rd表示皇后不能放的位置,按位取反后表示能放的位置,和maxn(二进制全是1的数)取&操作,就提取出所有可以放置皇后的位置, 用for循环或者while 循环枚举所有位可以为1的位置,然后去放置皇后,每次枚举完之后,将用于表示能放置皇后的数减去该位置二进制的数十进制化后的数,放置后继续枚举下一行可以放置皇后的地方,直到枚举到第一行结束。
代码:
八皇后:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<math.h>
#include<set>
#include<numeric>
#include<string>
#include<string.h>
#include<iterator>
#include<map>
#include<unordered_map>
#include<stack>
#include<list>
#include<queue>
#include<iomanip>
#include<deque>
typedef long long ll;
typedef pair<ll, ll>PII;
const int N = 50;
char s[N][N];
ll col[N], dia[N], udia[N];
ll n;
void dfs(ll x)
{
if (x == n)
{
for (int i = 0; i < n; i++)cout << s[i] << '\n';
cout << '\n';
return;
}
for (int i = 0; i < n; i++)
{
if (!col[i] && !dia[i + x] && !udia[n - i + x])
{
col[i] = 1, dia[i + x] = 1, udia[n - i + x] = 1;
s[x][i] = 'Q';
dfs(x + 1);
s[x][i] = '.';
col[i] = 0, dia[x + i] = 0, udia[n - i + x] = 0;
}
}
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
s[i][j] = '.';
}
}
dfs(0);
return 0;
}
优化之后:
#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
#include<math.h>
#include<set>
#include<numeric>
#include<string>
#include<string.h>
#include<iterator>
#include<map>
#include<unordered_map>
#include<stack>
#include<list>
#include<queue>
#include<iomanip>
#include<deque>
typedef long long ll;
typedef pair<ll, ll>PII;
const int N = 5050;
int n;
int upper_limit; // 111...1111 n bits
int ans = 0;
void test(int row, int ld, int rd)
{
if (row != upper_limit)
{
//这一行放过的 并 已经放过的左对角线 并 已经放过的右对角线
int num = upper_limit & ~(row | ld | rd);//(row|ld|rd)表示不能放的位置,取反后表示能放的位置,和全是1的数&操作,得出皇后能放置的位置
while (num != 0) //枚举皇后位置
{
int p = num & (-num); //求最后一个1在哪一位
num = num ^ p; // 将p二进制为1的位置在pos中置为0
int lld = (ld | p) << 1, rrd = (rd | p) >> 1;
test(row | p, lld, rrd);// row | p 把p位置的二进制为1的位置放上皇后,(ld | p) << 1 更新ld的下一层不能放(该位置的左边一个)的位置,(rd | p) >> 1 更新rd的下一层不能放(该节点的右边一个位置)的位置
}
}
else ans++;//找到一个成功放置的方法,将数量加一
}
int main() {
ans = 0;
cin >> n;
upper_limit = (1 << n) - 1;//将所有的位数全部置1
clock_t start, finish;
double dtime;
start = clock();
test(0, 0, 0);
finish = clock();
dtime = (double)(finish - start) / CLOCKS_PER_SEC;//1秒中CPU运行运行的时钟周期数
cout << "Time is " << dtime << '\n';
cout << "共有多少种情况: " << ans << '\n';
return 0;
}