When recursion occurs in the IF judgment...

Source: Internet
Author: User

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;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.