首页 > 技术文章 > 【算法】深度优先搜索

yznnnn 2019-03-12 22:07 原文

深度优先搜索(DFS)是一种极其经典的算法,最好的理解例子是全排列问题。

现有数字 1~5,对他们进行全排列,共有几种排法?

#include<stdio.h>
int data[5]={1,2,3,4,5};
int perm[5]={0};
bool book[5]={false};

void dfs(int step)
{
	int i;
	if(step==5)
	{
		for(i=0;i<5;i++)
		{
			printf("%d ",perm[i]);
		}
		printf("\n");
		return;
	}
	for(i=0;i<5;i++)
	{
		if(!book[i])
		{
			book[i]=true;
			perm[step]=data[i];
			dfs(step+1);
			book[i]=false;
		}
	}
	return;
}
int main()
{
	dfs(0);
	
	
	 
	return 0;
}

推荐阅读