1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
|
// Pseudocode
// In order to apply backtracking to a specific class of
// problems, one must provide the data P for the particular
// instance of the problem that is to be solved, and six
// procedural parameters, root, reject, accept, first,
// next, and output. These procedures should take the
// instance data P as a parameter and should do the following:
// root(P): return the partial candidate at the root of the search tree.
// reject(P,c): return true only if the partial candidate c is not worth completing.
// accept(P,c): return true if c is a solution of P, and false otherwise.
// first(P,c): generate the first extension of candidate c.
// next(P,s): generate the next alternative extension of a candidate, after the extension s.
// output(P,c): use the solution c of P, as appropriate to the application.
// The backtracking algorithm reduces then to the call bt(root(P)), where bt is the following recursive procedure:
// procedure bt(c)
// if reject(P,c) then return
// if accept(P,c) then output(P,c)
// s <- first(P,c)
// while s != null do
// bt(s)
// s <- next(P,s)
#ifndef BACKTRACK
#define BACKTRACK
#include <vector>
using std::vector;
template <class T>
class Backtrack
{
private:
vector<T> P;
vector<T> (*root)(vector<T>);
bool (*reject)(vector<T>, vector<T>);
bool (*accept)(vector<T>, vector<T>);
vector<T> (*first)(vector<T>, vector<T>);
vector<T> (*next)(vector<T>, vector<T>);
void (*output)(vector<T>, vector<T>);
void bt(vector<T>& c)
{
if( reject(P, c) )
return;
if( accept(P, c) )
output(P, c);
vector<T> s = first(P, c);
while( s.size() != 0 )
{
bt(s);
s = next(P, s);
}
}
public:
Backtrack<T>( vector<T> (*root)(vector<T>),
bool (*reject)(vector<T>, vector<T>),
bool (*accept)(vector<T>, vector<T>),
vector<T> (*first)(vector<T>, vector<T>),
vector<T> (*next)(vector<T>, vector<T>),
void (*output)(vector<T>, vector<T>) )
{
this->root = root;
this->reject = reject;
this->accept = accept;
this->first = first;
this->next = next;
this->output = output;
}
void backtrack()
{
bt(root(P));
}
};
#endif
|