回溯是一种DFS算法,当然,作为一种硬性枚举的算法,它的时间复杂度是O(2^n)这样一个数字,只能解决N≤15的问题,如果数字稍大一点,可能就会出现超时的现象,这是毋庸置疑的。下面的代码是用回溯算法解决的八皇后问题:
#include <cstdio>
using namespace std;
const int N = 2e1 + 10;
int n,res[N],cnt = 0;
bool used[N];
bool check(int x,int y)
{
for (int i = x - 1,j = y - 1;i >= 1 && j >= 1;--i,--j)
{
if (res[i] == j) return true;
}
for (int i = x - 1,j = y + 1;i >= 1 && j <= n;--i,++j)
{
if (res[i] == j) return true;
}
return false;
}
void dfs(int cur)
{
if (cur == n + 1)
{
cnt ++;
if (cnt <= 3)
{
for (int i = 1;i <= n;++i)
{
printf("%d ",res[i]);
}
printf("\n");
}
return ;
}
for (int i = 1;i <= n;++i)
{
if (used[i] || check(cur,i)) continue;
used[i] = true;
res[cur] = i;
dfs(cur + 1);
used[i] = false;
}
}
int main()
{
scanf("%d",&n);
dfs(1);
printf("%d",cnt);
return 0;
}很显然,这段代码运用了多处for循环,复杂度一定是只高不低的。因此,我想请教一下各位大佬,有没有能够解决这种问题的优化方案?