1. All permutations of the first n natural numbers:
1#include <iostream>2#include <cstdio>3#include <cstring>4 5 using namespacestd;6 7 intCount=1, N;8 BOOL*b;9 int*A;Ten One voidDfsint); A - intMain () - { thescanf"%d",&n); -b=New BOOL[n+1]; -A=New int[n+1]; -memset (b,0, n+1);//We can't write sizeof (b), B is a variable pointer +Dfs1); - return 0; + } A voidDfsintt) at { - for(intI=1; i<=n;i++) - { - if(B[i])Continue; -b[i]=1; -a[t]=i; in if(t==N) - { toprintf"%d", count++); + for(intj=1; j<=n;j++) printf ("%d", A[j]); -Puts""); theb[i]=0; * return; $ }Panax NotoginsengDFS (t+1); -b[i]=0; the } +}
View Code
2. Whether the maze has access (DFS):
1#include <iostream>2#include <cstdio>3#include <cstring>4 5 using namespacestd;6 7 Const intn= -;8 CharMi_gong[n][n];9 BOOLB[n][n];Ten intdx[]={1,-1,0,0},dy[]={0,0,1,-1}; One intN,m,x1,x2,y1,y2; A BOOLBB; - - voidCreate (); the BOOLCanmove (intXinty); - voidDfs (intXintYintstep); - - intMain () + { - Create (); +Dfs (X1,y1,0); A if(bb==0) puts ("The little mouse couldn't get out and was choked to death. "); at return 0; - } - voidCreate () - { -Puts"Enter the number of rows in the maze and the start and end point of the mouse, and then enter the maze for each lattice point. Representative can go, #代表不可以走. "); -scanf"%d%d%d%d%d%d",&n,&m,&x1,&y1,&x2,&y2); in for(intI=1; i<=n;i++) - { to GetChar (); + for(intj=1; j<=m;j++) - { thescanf"%c",&mi_gong[i][j]); * } $ }Panax Notoginseng } - BOOLCanmove (intXinty) the { + returnX>0&&x<=n&&y>0&&y<=m&&mi_gong[x][y]=='.'&&b[x][y]==0; A } the voidDfs (intXintYintStep) + { - if(BB)return; $ if(x==x2&&y==y2) $ { -Puts"The little mouse can get out of the maze. "); -bb=1; the return; - }Wuyi intTx,ty; theb[x][y]=1; - for(intI=0;i<4; i++) Wu { -tx=x+Dx[i]; Aboutty=y+Dy[i]; $ if(Canmove (Tx,ty)) Dfs (tx,ty,step+1); - } -b[x][y]=0; -}
View Code
3. Given n positive integers a1,a2,a3,..., an, and a positive integer k, ask whether it is possible to select several numbers from the n number to make it and K:
1#include <iostream>2#include <cstdio>3#include <cstring>4 5 using namespacestd;6 7 BOOLans;8 intn,k,*a,*s;9 voidDfsintIintsum);Ten One intMain () A { -scanf"%d%d",&n,&k); -A=New int[n]; thes=New int[n]; - for(intI=0; i<n;i++) scanf ("%d",&a[i]); - ints0=0; - for(inti=n-1; i>=0; i--) s0+=a[i],s[i]=S0; +Dfs0,0); - if(ANS) cout<<"true"; + return 0; A } at voidDfsintIintsum) - { - if(ans| | sum>k| | SUM+S[I]<K)return; - if(i==N) - { - if(sum==k) ans=true; in return; - } toDFS (i+1, sum+a[i]); +DFS (i+1, sum); -}
View Code
Search Algorithm Little Exercise