The depth-first search algorithm ( English:depth-first-search, or DFS) is an algorithm for traversing or searching a tree or graph. Traverse the tree's nodes along the depth of the tree, searching the branches of the tree as deep as possible. When the edge of Node V has been explored or the node does not meet the conditions at the time of search, the search will go back to the starting node of the side where node V was found. The entire process is repeated until all nodes have been accessed. belongs to the blind search, the worst case algorithm time complexity is O (!n). (Wiki)
DFS often accompanies many optimization strategies in the search process, adding pruning functions, or combining with dynamic programming.
Let's use a seemingly simple example to understand DFS. = =
/** * Add an integer n into k addend and cannot be duplicated. e.g. n=7 k=2--(1,6) (2,5) (3,4)//(4,3) and so on as duplicates * * How many methods to divide and print each sub-method * * 0<n<=200 1<k<=7*/
#include<iostream>using namespacestd;intsum =0;intfinalexp[8];voidNumdivision (intNumintPartsintCurr =1,intLevel =1){ if(Parts = =1){//search for the condition at the end of the node .sum++;//get a split method ints =0; inti; for(i =1; I < level; i++) {s+=Finalexp[i]; cout<< Finalexp[i] <<" + "; } cout<< Num <<" = "<< Num+s <<Endl; return ; } for(inti = Curr; I <= num/parts; i++) {Finalexp[level]= i;//Storage ResultsNumdivision (num-i,parts-1, i,level+1);//Core backtracking recursion }}intMain () {numdivision (7,3); cout<< sum <<Endl; return 0;} //Achieve
The example shows the most common framework for DFS.
int arr[]//Jie
DFS () {
if () {//Search reaches end
Solution Set operation
}
if () {//for (), while ()
DFS ()//post-judgment backtracking recursion
}
}
The difficulty lies in analyzing the problem, how to get the end condition of the search node, how to change the parameters of recursion ... .
A backtracking algorithm, as the encyclopedia says, is an algorithm for traversing or searching a tree. We can plot the problem into a tree-like structure.
The simple demo time of Dfs is over ~ I hope it helps you.
DFS (depth first/backtracking algorithm) one