forked from 1989chenguo/CloudComputingLabs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsudoku_min_arity.cc
More file actions
62 lines (51 loc) · 1.2 KB
/
Copy pathsudoku_min_arity.cc
File metadata and controls
62 lines (51 loc) · 1.2 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <assert.h>
#include <algorithm>
#include "sudoku.h"
static int arity(int cell)
{
bool occupied[10] = {false};
for (int i = 0; i < NEIGHBOR; ++i) {
int neighbor = neighbors[cell][i];
occupied[board[neighbor]] = true;
}
return std::count(occupied+1, occupied+10, false);
}
static void find_min_arity(int space)
{
int cell = spaces[space];
int min_space = space;
int min_arity = arity(cell);
for (int sp = space+1; sp < nspaces && min_arity > 1; ++sp) {
int cur_arity = arity(spaces[sp]);
if (cur_arity < min_arity) {
min_arity = cur_arity;
min_space = sp;
}
}
if (space != min_space) {
std::swap(spaces[min_space], spaces[space]);
}
}
bool solve_sudoku_min_arity(int which_space)
{
if (which_space >= nspaces) {
return true;
}
find_min_arity(which_space);
int cell = spaces[which_space];
for (int guess = 1; guess <= NUM; ++guess) {
if (available(guess, cell)) {
// hold
assert(board[cell] == 0);
board[cell] = guess;
// try
if (solve_sudoku_min_arity(which_space+1)) {
return true;
}
// unhold
assert(board[cell] == guess);
board[cell] = 0;
}
}
return false;
}