【DFS】错位排列

Description

按字典顺序输出错位排列

Input

n (n<=10)

Output

字典顺序的错位排列

Sample Input

4

Sample Output

2 1 4 3 
2 3 4 1 
2 4 1 3 
3 1 4 2 
3 4 1 2 
3 4 2 1 
4 1 2 3 
4 3 1 2 
4 3 2 1

//数字间有一空格

思路:
暴搜

代码:

#include<iostream>
#include<cstdio>
using namespace std;
int n,b[105];
bool a[105]={0};
void dfs(int k)
{
	if(k==n+1)//判断此方案是否搜完
	{
		for(int i=1;i<=n;i++)
			printf("%d ",b[i]);
		printf("\n");//输出
	}
	for(int i=1;i<=n;i++)
	{
		if(a[i]==0 && i!=k)//判断此数用过没和在不在原位
		{
			a[i]=1;//把此数判为用过
			b[k]=i;//把此数放进栈里
			dfs(k+1);
			b[k]=0;//把此数拿出栈里
			a[i]=0;//把此数判回没用过
		} 
	}
}
int main()
{
	scanf("%d",&n);
	dfs(1);//直接深搜
	return 0;
} 


猜你喜欢

转载自blog.csdn.net/SSL_wujiajie/article/details/82712526