Description–
解题思路–
h[x][y]表示x行有没有y数,l[x][y]表示列,g[x][y]表示该小矩阵
代码–
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
int a[100];
bool gg, l[10][10], h[10][10], g[10][10];
string s;
int hll(int xx)
{
int x = xx / 9 + 1;
int y = xx % 9, yy;
if (xx % 9 == 0) x--, y = 9;
if (x <= 3)
{ if (y <= 3) yy = 1; else if (y <= 6) yy = 2; else yy = 3; }
if (x > 3 && x <= 6)
{ if (y <= 3) yy = 4; else if (y <= 6) yy = 5; else yy = 6; }
if (x > 6)
{ if (y <= 3) yy = 7; else if (y <= 6) yy = 8; else yy = 9; }
return yy;
}
void dfs(int lev)
{
if (gg) return ;
if (lev > 81)
{
gg = 1;
for (int i = 1; i <= 81; ++i)
printf("%d", a[i]);
printf("\n");
return ;
}
if (a[lev] != 0)
{ dfs(lev + 1); return ; }
int x = lev / 9 + 1;
int y = lev % 9;
int z = hll(lev);
if (lev % 9 == 0) x--, y = 9;
for (int i = 1; i <= 9; ++i)
{
if (!h[x][i] && !l[y][i] && !g[z][i])
{
a[lev] = i;
h[x][i] = l[y][i] = g[z][i] = 1;
dfs(lev + 1);
a[lev] = 0;
h[x][i] = l[y][i] = g[z][i] = 0;
}
}
}
int main()
{
cin >> s;
while (s != "end")
{
memset (a, 0, sizeof (a));
memset (h, 0, sizeof (h));
memset (l, 0, sizeof (l));
memset (g, 0, sizeof (g));
for (int i = 1; i <= 81; ++i)
if (s[i - 1] != '.')
{
a[i] = s[i - 1] - '0';
int x = i / 9 + 1;
int y = i % 9;
if (i % 9 == 0) x--, y = 9;
h[x][a[i]] = l[y][a[i]] = g[hll(i)][a[i]] = 1;
}
gg = 0, dfs(1);
cin >> s;
}
return 0;
}