[Ybtoj high-efficiency advanced 1.4] B. Sudoku game [Deep Search]

Insert picture description here

analysis

Use string input to
convert it into a numeric value into the array a
array lll Statistics the use of the current row number
arrayrrr Statistics the usage of current column numbers
ArrayfffStatistics the current usage of 3*3 grid numbers
Enumerate the numbers that can be filled in the current grid

Upload code

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

int a[10][10],l[10][10],r[10][10],f[10][10][10],p;
string s;

int find(int x) 
{
    
    
	if(x<4) return 1;
	if(x<7) return 2;
	return 3;
}

void dfs(int x,int y)
{
    
    
	if(p) return;//已经有答案了
	if(x>9)
	{
    
    
		for(int i=1;i<=9;i++)
		{
    
    
			for(int j=1;j<=9;j++)
			{
    
    
				cout<<a[i][j];
			}
		}
		cout<<endl;
		p=1;
		return;
	} 
	if(a[x][y])
	{
    
    
		if(y==9) dfs(x+1,1);
		else dfs(x,y+1);
	}
	for(int i=1;i<=9;i++)
	{
    
    
		if(!l[x][i]&&!r[y][i]&&!f[find(x)][find(y)][i]&&!a[x][y])
		{
    
    
			a[x][y]=i;
			l[x][i]=r[y][i]=f[find(x)][find(y)][i]=1;
			if(y==9) dfs(x+1,1);
			else dfs(x,y+1);
			a[x][y]=0;
			l[x][i]=r[y][i]=f[find(x)][find(y)][i]=0;//回溯 
		}
	}
}

int main()
{
    
    
	while(cin>>s)
	{
    
    
		if(s=="end") return 0;
		p=0;
		memset(l,0,sizeof(l));
		memset(r,0,sizeof(r));
		memset(f,0,sizeof(f));
		for(int i=1;i<=9;i++)
		{
    
    
			for(int j=1;j<=9;j++)
			{
    
    
				if(s[(i-1)*9+j-1]!='.')
				{
    
    
					a[i][j]=s[(i-1)*9+j-1]-48;
					l[i][a[i][j]]=1;
					r[j][a[i][j]]=1;
					f[find(i)][find(j)][a[i][j]]=1;
				}
				else a[i][j]=0;
			}
		}
		dfs(1,1);
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/dglyr/article/details/112394384