-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsudoku.cpp
92 lines (77 loc) · 1.79 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <iostream>
#include <cassert>
#include <algorithm>
#include <utility>
#include "sudoku.h"
using namespace std;
Sudoku::Sudoku( int k, int* d )
: k_ ( k )
{
data_ = new Entry* [ size() ];
for( int i=0; i<size(); ++i )
data_[i] = new Entry[size()];
for( int row=0; row<size(); ++row )
for( int col=0; col<size(); ++col )
data_[row][col] = make_pair( d[(row*k*k) + col], d[(row*k*k) + col]<0 );
}
Sudoku::~Sudoku()
{
for( int i=0; i<size(); ++i )
delete[] data_[i];
delete[] data_;
}
int Sudoku::operator() ( int i, int j )
{
assert( i>=0 && i<size() );
assert( j>=0 && j<size() );
return data_[i][j].first;
}
bool Sudoku::writable( int i, int j )
{
assert( i>=0 && i<size() );
assert( j>=0 && j<size() );
return data_[i][j].second;
}
void Sudoku::set ( int i, int j, int v )
{
assert( i>=0 && i<size() );
assert( j>=0 && j<size() );
assert( data_[i][j].second );
data_[i][j].first = v;
}
bool Sudoku::is_solved( void )
{
// rows?
for( int row=0; row<size(); ++row )
for( int val=0; val<size(); ++val )
{
int cnt=0;
for( int col=0; col<size(); ++col )
if( data_[row][col].first == val )
++cnt;
if( cnt != 1 ) return false;
}
// cols?
for( int col=0; col<size(); ++col )
for( int val=0; val<size(); ++val )
{
int cnt=0;
for( int row=0; row<size(); ++row )
if( data_[row][col].first == val )
++cnt;
if( cnt != 1 ) return false;
}
// blocks
for( int brow=0; brow<size(); brow += k_ )
for( int bcol=0; bcol<size(); bcol += k_ )
for( int val=0; val<size(); ++val )
{
int cnt=0;
for( int row=0; row<k_; ++row )
for( int col=0; col<k_; ++col )
if( data_[brow+row][bcol+col].first == val )
++cnt;
if( cnt != 1 ) return false;
}
return true;
}