跳到正文

算法·理论

【求助】算法优化

_0TwT0_约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年8月12日
收录
2026年8月17日
更新
2026年8月17日
篇幅
约 2 分钟

版本

  1. v1当前

回溯是一种DFS算法,当然,作为一种硬性枚举的算法,它的时间复杂度是O(2^n)这样一个数字,只能解决N≤15的问题,如果数字稍大一点,可能就会出现超时的现象,这是毋庸置疑的。下面的代码是用回溯算法解决的八皇后问题:

C++
#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循环,复杂度一定是只高不低的。因此,我想请教一下各位大佬,有没有能够解决这种问题的优化方案?

原文