-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbacktrack.h
83 lines (68 loc) · 1.68 KB
/
backtrack.h
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
77
78
79
80
81
82
83
#ifndef _BACKTRACK_H_
#define _BACKTRACK_H_
#include <stack>
#include <ostream>
//#define TRACE_BACKTRACK
#ifdef TRACE_BACKTRACK
#include <sstream>
#define TRACE(a)\
{\
std::ostringstream oss;\
oss << a;\
_Output << oss.str() << std::endl;\
}
#else
#define TRACE(a)
#endif
template <typename T>
class Backtrack
{
public:
Backtrack(std::ostream & os);
void operator()(T & candidate);
unsigned getNbSolution() {return _NbSolution;}
unsigned getNbCandidate() {return _NbCandidate;}
private:
Backtrack(Backtrack<T> const &);
void operator= (Backtrack<T> const &);
unsigned _NbSolution;
unsigned _NbCandidate;
std::ostream & _Output;
};
template <typename T>
Backtrack<T>::Backtrack(std::ostream & os)
: _NbSolution(0)
, _NbCandidate(0)
, _Output(os)
{
// nothing
}
template <typename T>
void Backtrack<T>::operator()(T & candidate)
{
TRACE("new candidate:\n" << candidate);
++_NbCandidate;
if (!candidate.is_valid()) {
TRACE("not valid");
return;
}
if (candidate.is_complete()) {
// complete and valid => solution
TRACE("solution");
++_NbSolution;
_Output << candidate << std::endl;
return;
}
// As this algo takes candidate as a reference, it needs to be copied before generating children.
T next = candidate;
// valid and not complete: generate first extension...
TRACE("generate first");
next.first();
do {
//... test every possible extensions
operator()(next); // recurse
TRACE("generate next");
} while (next.next());
TRACE("no more possibilities for this extension");
}
#endif