Introduction to Backtracking : http://en.wikipedia.org/wiki/Backtracking
Implementation [1]:
Simple Exercise : Use the above template to count the number of permutations of 1, 2, 3... n (n > 5) in which 4 and 5 are not neighbours.
[1] - http://www.cs.sunysb.edu/~skiena/392/programs/
Implementation [1]:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
int finished = 0; /* found all solutions yet? */ | |
template <class T> | |
backtrack(int a[], int k, T * input) | |
{ | |
T c[MAXCANDIDATES]; /* candidates for next position */ | |
int ncandidates; /* next position candidate count */ | |
int i; /* counter */ | |
if (is_a_solution(a,k,input)) | |
process_solution(a,k,input); | |
else { | |
k = k+1; | |
construct_candidates(a,k,input,c,&ncandidates); | |
for (i=0; i<ncandidates; i++) { | |
a[k] = c[i]; | |
backtrack(a,k,input); | |
if (finished) return; /* terminate early */ | |
} | |
} | |
} |
Simple Exercise : Use the above template to count the number of permutations of 1, 2, 3... n (n > 5) in which 4 and 5 are not neighbours.
[1] - http://www.cs.sunysb.edu/~skiena/392/programs/
No comments:
Post a Comment