题意:数独问题,每行每列以及每块都有1~9的数字
分析:一个一个遍历会很慢。先将0的位子用vector存起来,然后用rflag[i][num] = 1 / 0表示在第i行数字num是否出现过,其他的类似,这样在用DFS就很快了,数据问题,反着搜索会更快。。。
/************************************************
* Author :Running_Time
* Created Time :2015/11/10 星期二 15:43:47
* File Name :POJ_2676.cpp
************************************************/ #include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std; #define lson l, mid, rt << 1
#define rson mid + 1, r, rt << 1 | 1
typedef long long ll;
const int N = 1e5 + 10;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
const double EPS = 1e-10;
const double PI = acos (-1.0);
struct Pos {
int x, y;
Pos () {}
Pos (int x, int y) : x (x), y (y) {}
};
vector<Pos> blank;
int mp[11][11];
int rflag[11][11], cflag[11][11], bflag[11][11]; int get_id(int x, int y) {
int xx = x / 3;
int yy = y / 3;
return xx * 3 + yy;
} void set_num(int x, int y, int num, int f) {
rflag[x][num] = f;
cflag[y][num] = f;
bflag[get_id (x, y)][num] = f;
} bool ok(int x, int y, int num) {
return !rflag[x][num] && !cflag[y][num] && !bflag[get_id (x, y)][num];
} bool DFS(int cnt) {
if (cnt < 0) return true;
int x = blank[cnt].x, y = blank[cnt].y;
for (int i=1; i<=9; ++i) {
if (!ok (x, y, i)) continue;
mp[x][y] = i;
set_num (x, y, i, 1);
if (DFS (cnt - 1)) return true;
set_num (x, y, i, 0);
}
return false;
} int main(void) {
int T; scanf ("%d", &T);
while (T--) {
for (int i=0; i<9; ++i) {
for (int j=0; j<9; ++j) {
scanf ("%1d", &mp[i][j]);
}
}
blank.clear ();
memset (rflag, 0, sizeof (rflag));
memset (cflag, 0, sizeof (cflag));
memset (bflag, 0, sizeof (bflag));
for (int i=0; i<9; ++i) {
for (int j=0; j<9; ++j) {
if (mp[i][j] == 0) blank.push_back (Pos (i, j));
else {
set_num (i, j, mp[i][j], 1);
}
}
}
if (DFS (blank.size () - 1)) {
for (int i=0; i<9; ++i) {
for (int j=0; j<9; ++j) {
printf ("%d", mp[i][j]);
}
puts ("");
}
}
else puts ("233");
} //cout << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC << " s.\n"; return 0;
}