DFS 练习 (这篇真的是随笔)

目的:

输入:

3

输出:

1 2 3

1 3 2

2 1 3

2 3 1

3 1 2

3 2 1

代码如下:

 1 #include<stdio.h>
 2 int a[20],b[20],n;
 3 void dfs(int t)
 4 {
 5     int i,j;
 6     if (t>n)//循环终止条件 , 输出结果
 7     {
 8         for(j=1;j<n;j++)
 9             printf("%d ",a[j]);
10         printf("%d\n",a[n]);
11     }
12     else for (i=1;i<=n;i++)
13         if (b[i]==1)//如果当前数字可用
14     {
15         b[i]=0;
16         a[t]=i;
17         dfs(t+1);//进入下一层循环
18         b[i]=1;//退出循环,恢复状态
19     }
20 
21 }
22 int main()
23 {
24     int k;
25     while(scanf("%d",&n)!=EOF)
26     {
27         a[0]=0;
28         for(k=0;k<20;k++)
29             b[k]=1;//1代表下标为k的数没有使用过
30         dfs(1);//第一次进入循环
31     }
32     return 0;
33 }

 

 

posted @ 2013-12-19 22:30  Jeremy Wu  阅读(311)  评论(0)    收藏  举报