-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbacktracking.cpp
More file actions
46 lines (40 loc) · 1.55 KB
/
backtracking.cpp
File metadata and controls
46 lines (40 loc) · 1.55 KB
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
namespace BackTracking {
int numberOfNodes;
int numberOfBacktracks;
bool backTrack(Matrix &cur, vector< Cell >&unassigned) {
numberOfNodes++;
if (!isConsistent(cur)) {
numberOfBacktracks++;
return false;
}
if (unassigned.empty()) return true;
if (timer.timesUp()) return false;
int dim = cur.size();
int nxtIdx = VariableOrdering::chooseNextIndex(cur, unassigned);
swap(unassigned[nxtIdx], unassigned[unassigned.size()-1]);
const Cell p = unassigned.back();
unassigned.pop_back();
for (int x : ValueOrdering::getValueOrderWithoutDomain(cur, p)) {
cur[p.first][p.second] = x;
if (backTrack(cur, unassigned)) return true;
cur[p.first][p.second] = 0;
}
unassigned.push_back(p);
swap(unassigned[nxtIdx], unassigned[unassigned.size()-1]);
return false;
}
void solveWithBackTrack(Matrix start) {
vector<Cell> unassigned = getUnassignedPlaces(start);
numberOfNodes = numberOfBacktracks = 0;
if (backTrack(start, unassigned)) {
cout << "Found a solution with backtracking:" << endl;
printMat(start);
} else {
cout << "Solution not found!" << endl;
numberOfNodes = numberOfBacktracks = -1;
}
cout << "Number of nodes: " << numberOfNodes << endl;
cout << "Number of backtracks: " << numberOfBacktracks << endl;
cout << endl;
}
}