## ACM PKU 2636 Sudoku http://acm.pku.edu.cn/JudgeOnline/problem?id=2676

数独问题：
搜索时，注意下标；
#include <iostream>
using namespace std;

int num[11][11];
int Case;

void input()
{

memset(num,0,sizeof(num));

int i,j;
for (i = 0;i <9; i++)
for (j = 0;j < 9; j++)
{
char a;
cin >> a;
num[i][j] = a - '0';
}
}

void output()
{
int i,j;
for (i = 0;i < 9; i++)
{
for (j = 0;j < 9; j++)
cout<<num[i][j];
cout<<endl;
}
}

bool row( int n , int figure)
{
int i = 0 ;
for (; i < 9; i++)
{
if (i == n % 9)   continue;
if (num[n/9][i] == figure)
return false;
}
return true;
}

bool column(int n, int figure)
{
int i = 0;
for (;i < 9; i++)
{
if (i == n / 9 )   continue;
if (num[i][n%9] == figure)
return false;
}
return true;
}

bool squre(int n, int figure)
{
int i, j ;
int t0 = n/9/3*3, t1 = (n%9)/3*3;
for (i = t0 ;i < t0+3; i++)
for (j = t1;j < t1+3; j++)
{
if (i == n/9 && j == n%9)  continue;
if (num[i][j] == figure)
return false;
}
return true;
}

int solve(int deep)
{
int i;
if (deep == -1) return 1;
if (num[deep/9][deep%9] != 0)
return solve (deep-1);
else
{
for(i = 1; i <= 9 ;i++)
{
num[deep/9][deep%9] = i;
if (row(deep,i) && column(deep,i) && squre(deep,i))
{
if(solve(deep-1))
return 1;
}
num[deep/9][deep%9] = 0;
}
return 0;
}
}

int main ()
{
cin >> Case;
while (Case--)
{
input();
solve(80);
output();
}
return 0;
}


posted on 2011-05-06 18:52  _Clarence  阅读(85)  评论(0编辑  收藏

• 随笔 - 0
• 文章 - 162
• 评论 - 3
• 引用 - 0