这道题是DFS。看了discuss,说是倒着搜。从8,8到0,0,应该是根据测试数据来的。
thestoryofsnow | 2676 | Accepted | 132K | 16MS | C++ | 2172B |
/*
ID: thestor1
LANG: C++
TASK: poj2676
*/
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <limits>
#include <string>
#include <vector>
#include <list>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <cassert>
using namespace std;
bool bexists[3][3][9], rexists[9][9], cexists[9][9];
void printSudoku(char sudoku[][9])
{
// printf("[debug]sudoku:\n");
for (int r = 0; r < 9; ++r)
{
for (int c = 0; c < 9; ++c)
{
printf("%c", sudoku[r][c]);
}
printf("\n");
}
}
bool solveSudoku(char sudoku[][9], int r, int c)
{
if (c == -1)
{
c = 8;
r--;
if (r == -1)
{
return true;
}
}
// printf("[debug]r: %d, c: %d\n", r, c);
int br = r / 3, bc = c / 3;
if (sudoku[r][c] == '0')
{
for (int n = 1; n <= 9; ++n)
{
if (bexists[br][bc][n - 1] || rexists[r][n - 1] || cexists[c][n - 1])
{
continue;
}
bexists[br][bc][n - 1] = true;
rexists[r][n - 1] = true;
cexists[c][n - 1] = true;
if (solveSudoku(sudoku, r, c - 1))
{
sudoku[r][c] = n + '0';
return true;
}
bexists[br][bc][n - 1] = false;
rexists[r][n - 1] = false;
cexists[c][n - 1] = false;
}
// tried all possible candidates and failed
return false;
}
else
{
return solveSudoku(sudoku, r, c - 1);
}
}
int main()
{
int T;
scanf("%d", &T);
char sudoku[9][9];
for (int t = 0; t < T; ++t)
{
for (int r = 0; r < 9; ++r)
{
scanf("%s", sudoku[r]);
}
// printSudoku(sudoku);
for (int r = 0; r < 9; ++r)
{
for (int n = 0; n < 9; ++n)
{
rexists[r][n] = false;
cexists[r][n] = false;
}
}
for (int br = 0; br < 3; ++br)
{
for (int bc = 0; bc < 3; ++bc)
{
for (int n = 0; n < 9; ++n)
{
bexists[br][bc][n] = false;
}
}
}
for (int r = 0; r < 9; ++r)
{
for (int c = 0; c < 9; ++c)
{
int n = sudoku[r][c] - '0';
int br = r / 3, bc = c / 3;
if (n != 0)
{
bexists[br][bc][n - 1] = true;
rexists[r][n - 1] = true;
cexists[c][n - 1] = true;
}
}
}
solveSudoku(sudoku, 8, 8);
printSudoku(sudoku);
}
return 0;
}