book[]数组对元素进行标记,进行判断遍历
#include<stdio.h>
#include<windows.h>
int a[
10], book[
10], n;
void dfs(
int step)
{
int i;
if (step == n +
1)
{
for (i =
1; i <= n; i++)
{
printf(
"%d ", a[i]);
}
printf(
"\n");
}
for (i =
1; i <=n; i++)
{
if (book[i] ==
0)
{
a[step] = i;
book[i] =
1;
dfs(step +
1);
book[i] =
0;
}
}
}
int main()
{
scanf_s(
"%d", &n);
dfs(
1);
system(
"pause");
return 0;
}
深度优先搜索基本模型
void dfs(int step) { 判断边界 尝试每一种可能 for (int i = 1; i <= n; i++) { 继续下一步dfs(step + 1); } 返回
}
转载请注明原文地址: https://ju.6miu.com/read-650230.html