#include <bits/stdc++.h>
using namespace std;
#define maxn 9
int board[maxn][maxn];
int points[maxn][maxn] = {
{6,6,6,6,6,6,6,6,6},
{6,7,7,7,7,7,7,7,6},
{6,7,8,8,8,8,8,7,6},
{6,7,8,9,9,9,8,7,6},
{6,7,8,9,10,9,8,7,6},
{6,7,8,9,9,9,8,7,6},
{6,7,8,8,8,8,8,7,6},
{6,7,7,7,7,7,7,7,6},
{6,6,6,6,6,6,6,6,6}
};
int maxPoints = 0;
int step = 0;
bool isValid(int i, int j) {
for (int col = 0; col < maxn; ++col) { //列冲突判断
if (col != j && board[i][j] == board[i][col])
return false;
}
for (int row = 0; row < maxn; ++row) { //行冲突判断
if (row != i && board[i][j] == board[row][j])
return false;
}
//关键点,转化为内部小九宫格的坐标,进行冲突判断
for (int row = i / 3 * 3; row < i / 3 * 3 + 3; ++row) {
for (int col = j / 3 * 3; col < j / 3 * 3 + 3; ++col) {
if (row != i && col != j && board[i][j] == board[row][col])
return false;
}
}
return true;
}
int getPoint() {
int sum = 0;
for(int i =0; i < maxn; i++) {
for(int j = 0; j < maxn; j++) {
sum += board[i][j] * points[i][j];
}
}
return sum;
}
void solve(int step) {
if(step == 81) {//找到1个可行解
int point = getPoint();
maxPoints = max(maxPoints, point);
return;
}
for(int i = 8; i >= 0; --i) {
for(int j = 8; j >= 0; --j) {
if(board[i][j] != 0)//已经有数字,跳过
continue;
for(int k = 1; k <= 9; ++k) {
board[i][j] = k;//试放
if(isValid(i, j)) { //不冲突
step++;
solve(step);
//回溯
step--;
board[i][j] = 0;
} else {//冲突
board[i][j] = 0;//回溯
}
}
return;//important, 9个数都放完了,到了这里,还没有答案,直接返回
}
}
}
int main() {
//freopen("data.in","r",stdin);
//freopen("data.out","w",stdout);
std::ios::sync_with_stdio(false);
for(int i = 0; i < maxn; i++) {
for(int j = 0; j < maxn; j++) {
cin >> board[i][j];
if(board[i][j] != 0) {
step++;
}
}
}
solve(step);
if(maxPoints != -1) {
cout << maxPoints << endl;
} else {
cout << -1 << endl;
}
return 0;
}
计蒜客 金字塔数独(dfs搜索)
最新推荐文章于 2022-04-03 22:52:32 发布