Depth first (DFS) template 1:
Void DFS (int K) // process step K
{If (k = N) // step N has been processed to reach the destination status
Output result
Else // process step K
For (INT I = 1; I <= m; I ++) // m is possible in step K.
{Process step K
DFS (k + 1); // enter step k + 1
}
}
Example 1: Multi-Arrangement
In the output, all multiple orders of N numbers are obtained from 1-M numbers. For example, n = 2 and M = 3 are arranged in multiple ways:
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
// Obtain the number of N records from 1 to M. The number can be repeated. # include <iostream> using namespace STD; int n, m, a [10]; void DFS (int K) {If (k = N) {for (INT I = 0; I <n; I ++) cout <A [I] <""; cout <Endl;} else for (INT I = 1; I <= m; I ++) {A [k] = I; DFS (k + 1 );}} int main () {CIN> m> N; DFS (0); Return 0 ;}View code
// Obtain n numbers from 1 to m and allow repeated numbers
# Include <iostream>
Using namespace STD;
Int n, m, a [10];
Void DFS (int K)
{If (k = N)
{For (INT I = 0; I <n; I ++)
Cout <A [I] <"; cout <Endl ;}
Else
For (INT I = 1; I <= m; I ++)
{A [k] = I; DFS (k + 1 );}
}
Int main ()
{
Cin> m> N;
DFS (0 );
Return 0;
}