第一篇博客,想把学会的代码记下了将来可以看看
POJ 2676
Sudoku
Sudoku is a very simple task. A square table with 9 rows and 9 columns
is divided to 9 smaller squares 3x3 as shown on the Figure. In some of the cells are written decimal digits from 1 to 9. The other cells are empty. The goal is to fill the empty cells with decimal digits from 1 to 9, one digit per cell, in such way that in
each row, in each column and in each marked 3x3 subsquare, all the digits from 1 to 9 to appear. Write a program to solve a given Sudoku-task
这道题题意大概就是9乘9的方格,每行每列四角的四个小3×3正方形都是由1到9的数字组成且不能重复。
首先1:对于四个小3*3的正方形要用k=(x/3)*3+y/3;来记录是第几个小正方形;
2:dfs中要注意用9进制来表示横纵坐标,感觉如果在DFS中立循环可能会炸。u=x*9+y+1; x=u/9;y=u%9;
#include<iostream>
#include<cstring>
using namespace std;
int cow[10][10];
int now[10][10];
int k1[10][10];
char num[10][10];
int temp;
bool is;
void dfs(int x,int y)
{
int u=x*9+y+1;
if(x==9)
{
is=true;//遍历全部的点
}
if(is==true)
return;
if(num[x][y]!='0')
{
dfs(u/9,u%9);//如果这个点不能赋值
return;
}
for(int i=1;i<=9&&!is;i++)
{
int k=(x/3)*3+y/3;
if(cow[x][i]==0&&now[y][i]==0&&k1[k][i]==0)//是否可以把i这个数填入num[x][y]中
{
cow[x][i]++;
now[y][i]++;
k1[k][i]++;
num[x][y]=i+'0';
dfs(u/9,u%9);
if(is==true)//很重要否则赋不了值
return;
num[x][y]='0';
cow[x][i]=0;
now[y][i]=0;
k1[k][i]=0;
}
}
}
int main()
{
int n;
cin>>n;
while(n--)
{
temp=0;
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
cin>>num[i][j];
if(num[i][j]=='0')
temp++;
}
}
memset(cow,0,sizeof(cow));
memset(now,0,sizeof(now));
memset(k1,0,sizeof(k1));
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
int k=num[i][j]-'0';
cow[i][k]++;
int k2=(i/3)*3+j/3;
k1[k2][k]++;
}
}
for(int j=0;j<9;j++)
{
for(int i=0;i<9;i++)
{
int k=num[i][j]-'0';
now[j][k]++;
}
}
is=false;
dfs(0,0);
for(int i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
cout<<num[i][j];
}
cout<<endl;
}
}
}