[DFS Notes] Thinking about dfs (index, status)

When the question says that there are a total of n numbers/n choices, and they are selected in order, such a dfs template is generally used

dfs(index,state){
   if(index==n)return;
   if(state not valid)cut; 
  for(choice):
   dfs(index+1,f(state,g(index)));
}

For example, the 8 queens problem: choose from 8 rows in turn, and choose 8 times. The state parameter is the vis tag.

and many more........

Here is my understanding of this template:

First of all, if is placed in front of dfs, that is to say, judgment is made before selection. What does this mean?

(1) Every time dfs, index is always increased by 1, because the essence of dfs call is to make a selection, so the index parameter can be understood as the number of selections. When index is passed in 0, because n selections are to be made, it will return when index==n, not when n-1 is returned

(2) If 0 is passed in, then when judging if, the number of selections is the already selected subscript + 1. Because the subscript 0 is also considered a selection, after the subscript 0 is selected, the index is 1 when the if is judged, and so on.

(3) The state parameter is the state after index selections are made. Because the state parameter is updated when making a selection, it is judged in if

, the corresponding state is the state where index times are selected (index is initially passed in 0)

(4) Because the value of the parameter is not changed, this template comes with a backtracking function.

 After making 3 selections, when the if judgment is made, the index is 3, the subscript 2 has been selected, and the state parameter is 0~2 state.

 

Guess you like

Origin blog.csdn.net/m0_52043808/article/details/123910682
dfs