-
Notifications
You must be signed in to change notification settings - Fork 9
/
sudoku.cpp
70 lines (66 loc) · 2.5 KB
/
sudoku.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
#include <amorgos.h>
#include <naxos.h>
#include <cstdlib>
#include <iostream>
using namespace std;
using namespace naxos;
void printSolution(NsIntVarArray* sol, int dim)
{
int i, j, k, l;
for (i = 0; i < dim; ++i) {
for (j = 0; j < dim; ++j) {
for (k = 0; k < dim; ++k) {
for (l = 0; l < dim; ++l)
cout << sol[dim * i + j][dim * k + l];
cout << " ";
}
cout << endl;
}
cout << endl;
}
}
int main(int argc, char* argv[])
{
try {
int i, j, sqrtn, n;
sqrtn = (argc > 1) ? atoi(argv[1]) : 3;
n = sqrtn * sqrtn;
NsProblemManager pm;
// PROBLEM STATEMENT //
NsIntVarArray *varRows, *varColumns, *varSquares;
varRows = new NsIntVarArray[n];
varColumns = new NsIntVarArray[n];
varSquares = new NsIntVarArray[n];
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
varRows[i].push_back(NsIntVar(pm, 1, n));
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j) {
varColumns[i].push_back(varRows[j][i]);
varSquares[i].push_back(
varRows[(i / sqrtn) * sqrtn + j / sqrtn]
[(i % sqrtn) * sqrtn + j % sqrtn]);
}
for (i = 0; i < n; ++i) {
pm.add(NsAllDiff(varRows[i]));
pm.add(NsAllDiff(varColumns[i]));
pm.add(NsAllDiff(varSquares[i]));
}
NsIntVarArray allVars;
for (i = 0; i < n; ++i)
for (j = 0; j < n; ++j)
allVars.push_back(varRows[i][j]);
// GOALS //
pm.addGoal(new AmDfsLabeling(allVars));
// SOLVING //
while (pm.nextSolution() != false) {
printSolution(varRows, sqrtn);
getchar();
}
} catch (exception& exc) {
cerr << exc.what() << "\n";
} catch (...) {
cerr << "Unknown exception"
<< "\n";
}
}