P1074 靶形数独 - 40

#include <bits/stdc++.h>
#define searchnext(x, y) y == 9 ? search(x + 1, 1) : search(x, y + 1)
using namespace std;
long long ans = 0;
int a[10][10];
void search(int, int);
void calc() {
  long long tmp = 0;
  for (int i = 1; i <= 9; i++) {
    for (int j = 1; j <= 9; j++) {
      if (i == 1 || i == 9 || j == 1 || j == 9) {
        tmp += 6 * a[i][j];
      } else if (abs(i - 9) == 1 || abs(i - 9) == 7 || abs(j - 9) == 1 ||
                 abs(j - 9) == 7) {
        tmp += 7 * a[i][j];
      } else if (abs(i - 9) == 2 || abs(i - 9) == 6 || abs(j - 9) == 2 ||
                 abs(j - 9) == 6) {
        tmp += 8 * a[i][j];
      } else if (abs(i - 9) == 5 || abs(i - 9) == 3 || abs(j - 9) == 5 ||
                 abs(j - 9) == 3) {
        tmp += 9 * a[i][j];
      } else
        tmp += 10 * a[i][j];
    }
  }
  ans = max(ans, tmp);
}
bool pd(int x, int y, int k) {
  for (int i = 1; i <= 9; i++)
    if (a[x][i] == k || a[i][y] == k)
      return 0;
  for (int i = (x - 1) / 3 * 3 + 1; i <= (x - 1) / 3 * 3 + 3; i++)
    for (int j = (y - 1) / 3 * 3 + 1; j <= (y - 1) / 3 * 3 + 3; j++)
      if (a[i][j] == k)
        return 0;
  return 1;
}
void search(int x, int y) {
  if (x == 10 && y == 1)
    calc();
  if (a[x][y] != 0) {
    searchnext(x, y);
  } else {
    for (int i = 9; i >= 1; i--)
      if (pd(x, y, i)) {
        a[x][y] = i;
        searchnext(x, y);
        a[x][y] = 0;
      }
  }
}
int main() {
  freopen("input.in", "r", stdin);
  for (int i = 1; i <= 9; i++)
    for (int j = 1; j <= 9; j++)
      scanf("%d", &a[i][j]);
  search(1, 1);
  if (ans)
    cout << ans;
  else
    cout << -1;
  return 0;
}

posted on 2016-11-16 19:35  蒟蒻konjac  阅读(158)  评论(0编辑  收藏  举报