填数独工具(用题目改编)

仅限九宫格

#include<bits/stdc++.h>
using namespace std;
const int N=11;
int a[N][N];
bool b[N][N],l[N][N],r[N][N];
inline void print()
{

	for(int i=1;i<=9;i++)
	{
		for(int j=1;j<=9;j++)
		{
			cout<<a[i][j]<<" ";

		}
		cout<<'\n';
	}
	exit(0);
}
inline void dfs(int x,int y)
{
	if(a[x][y]!=0)
	{
		if(x==9 and y==9)
			print();
		if(y==9)
			dfs(x+1,1);
		else dfs(x,y+1);
	}
	else
	{
		for(int i=1;i<=9;i++)
		{
			if(l[x][i] or r[i][y] or b[(x-1)/3*3+(y+2)/3][i]) continue;
			l[x][i]=r[i][y]=b[(x-1)/3*3+(y+2)/3][i] =true;
			a[x][y]=i;
			if(x==9 and y==9)
				print();
			if(y==9)
				dfs(x+1,1);
			else dfs(x,y+1);

			a[x][y]=0;
			l[x][i]=r[i][y]=b[(x-1)/3*3+(y+2)/3][i]=false;
		}

	}
}
inline void solve()
{
	for(int i=1;i<=9;i++)
		for(int j=1;j<=9;j++)
		{
			cin>>a[i][j];
			if(a[i][j]!=0)
			{
				int t=a[i][j];
				l[i][t]=r[t][j]=b[(i-1)/3*3+(j+2)/3][t]=true;
			}
		}
	dfs(1,1);
}
int main()
{
	solve();
	return 0;
}

输入没填好的数独题目,空位用0表示,每个位置之间要空格

5 个赞

给个hack:
输入:

9 0 0 8 0 0 0 0 0
0 0 0 0 0 0 5 0 0 
0 0 0 0 0 0 0 0 0 
0 2 0 0 1 0 0 0 3
0 1 0 0 0 0 0 6 0
0 0 0 4 0 0 0 7 0
7 0 8 6 0 0 0 0 0 
0 0 0 0 3 0 1 0 0 
4 0 0 0 0 0 2 0 0 

应输出:

9 7 2 8 5 3 6 1 4 
1 4 6 2 7 9 5 3 8 
5 8 3 1 4 6 7 2 9 
6 2 4 7 1 8 9 5 3 
8 1 7 3 9 5 4 6 2 
3 5 9 4 6 2 8 7 1 
7 9 8 6 2 1 3 4 5 
2 6 5 9 3 4 1 8 7 
4 3 1 5 8 7 2 9 6 

但是你的代码TLE了

1 个赞

3 个帖子被合并到现有话题中:垃圾站/废贴集中