basic model for depth-first search:
void Dfs (int step)
{
judge bounds
try every possible for (i=1;i<=n;i++)
{
continue next Dfs (step+1);
}
Return
}
task: Depth First search, put the 1-n into n boxes, there are several methods
C Implementation
#include <stdio.h>
int n,book[10],a[10];
void Dfs (int step)
{
int i;
if (step==n+1)
{
for (i=1;i<=n;i++)
printf ("%d", A[i]);
printf ("\ n");
return;
}
for (i=1;i<=n;i++)
{
if (book[i]==0)
{
a[step]=i;
Book[i]=1;
DFS (STEP+1); Continue searching until a book[i]=0 is completed
; Zero to make the next attempt}
return
;
int main ()
{
scanf ("%d", &n);
DFS (1);
return 0;
}
Python Implementation
def Depth_first_box (STEP): if step = = N+1:for I in range (1, n+1): Print ( Lists[i], end= ') print (' \ n ') return to J in range (1, n+1): If book[j]==0:book[ J]=1 lists[step]=j Depth_first_box (step+1) book[j]=0 return if __name__== ' __main__ ': Lists = [0] * One book = [0] * One n = Int (input ("Enter N:")) Depth_first_box (1)