-
Notifications
You must be signed in to change notification settings - Fork 0
/
backtrack_naive_unique.cpp
74 lines (68 loc) · 1.46 KB
/
backtrack_naive_unique.cpp
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
#include <iostream>
#include <stack>
#include "coords.h"
#include "backtrack_common.h"
#include "backtrack_naive_unique.h"
int soln_count(Grid& grid) {
std::stack<Spot> spots;
for(int i=0; i < 81; i++) {
Spot p = spot_of_idx(i);
if(grid.get(p) == 0) {
spots.push(p);
}
}
return soln_count_recurse(grid, spots);
}
int soln_count_recurse(Grid& grid, std::stack<Spot>& spots) {
Spot p = spots.top();
spots.pop();
int ret = 0;
for(int val=1; val <= 9; val++) {
if(grid.covered(p, val)) { continue; }
grid.set(p, val);
if(spots.empty()) {
ret += 1;
} else {
ret += soln_count_recurse(grid, spots);
}
}
grid.set(p, 0);
spots.push(p);
return ret;
}
int soln_count_solve(Grid& grid) {
int ret;
Grid solution;
std::stack<Spot> spots;
for(int i=0; i < 81; i++) {
Spot p = spot_of_idx(i);
if(grid.get(p) == 0) {
spots.push(p);
}
}
ret = soln_count_recurse_solve(grid, &solution, spots);
for(int i=0; i < 81; i++) {
grid.setmanual(solution.getmanual(i), i);
}
return ret;
}
int soln_count_recurse_solve(Grid& grid, Grid* solution, std::stack<Spot>& spots) {
Spot p = spots.top();
spots.pop();
int ret = 0;
for(int val=1; val <= 9; val++) {
if(grid.covered(p, val)) { continue; }
grid.set(p, val);
if(spots.empty()) {
for(int i=0; i < 81; i++) {
solution->setmanual(grid.getmanual(i), i);
}
ret += 1;
} else {
ret += soln_count_recurse_solve(grid, solution, spots);
}
}
grid.set(p, 0);
spots.push(p);
return ret;
}