The question of a word solitaire can be solved simply by void DFS (). It is not fun enough to change it to a memory-based search. In other words, in a book, we can see that the memory search is called the memorandum method, is a type of DP.
Simple search:
void dfs(int last,int length){if(length>longest) longest=length;int i;for(i=0;i<n;i++)if(ans[last][i]!=0)if(time[i]<2){time[i]++;dfs(i,length+ans[last][i]);time[i]--;}}
Change to memory-based search:
int dfs(int last){if(note[last]!=0) return note[last];int longest=0;int i;for(i=0;i<n;i++){if(ans[last][i]!=0)if(time[i]<2){time[i]++;if(longest<dfs(i)+ans[last][i])longest=dfs(i)+ans[last][i]; time[i]--;}}note[last]=longest;return longest;}
DFS () is returned. It was written as this by mistake.
int dfs(int last){if(note[last]!=0) return note[last];int longest=0;int i;for(i=0;i<n;i++){if(ans[last][i]!=0)if(time[i]<2)if(longest<dfs(i)+ans[last][i]){ //wrongtime[i]++; //wronglongest=dfs(i)+ans[last][i]; //wrongtime[i]--; //wrong}}note[last]=longest;return longest;}
In some cases, if () is an operation. The operation is executed first and the result is used as the condition for if () judgment. However, there are two DFS (). I wonder whether the two DFS () results are calculated separately or whether the results obtained in the IF judgment are directly used in the value assignment statement of the next sentence, I guess it should be the latter, or it will be much slower. The syntax below is similar, and the DFS () in IF is obtained.
int dfs(int last){if(note[last]!=0) return note[last];int longest=0;int i;for(i=0;i<n;i++){if(ans[last][i]!=0)if(time[i]<2){time[i]++;int t=dfs(i)+ans[last][i];if(t>longest) longest=t;time[i]--;}}note[last]=longest;return longest;}