[Ybt] [Basic calculation deep search example 2] Sudoku game

Sudoku game

Topic link: Sudoku game


Title description

Insert picture description here

Problem solving ideas

This question is obviously a deep search.

Three arrays are used to store the used numbers in the current row, column, and grid respectively.

Then search.

code

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

string T;
int ok;
int a[10][10];
int h[10][10],l[10][10],g[4][4][10];

int ch(int t)
{
    
    
	if(t<=3)
		return 1;
	if(t>3&&t<=6)
		return 2;
	if(t>6&&t<=9)
		return 3;
}

void dfs(int x,int y)
{
    
    
	if(ok)
		return;
	if(x>9&&y==1)
	{
    
    
		for(int i=1;i<=9;i++)
			for(int j=1;j<=9;j++)
				cout<<a[i][j];
		ok=1;
		return;
	}
	if(a[x][y])
	{
    
    
		if(y==9)
			dfs(x+1,1);
		else
			dfs(x,y+1);
	}
	else for(int i=1;i<=9;i++)
		if(!h[x][i]&&!l[y][i]&&!g[ch(x)][ch(y)][i])
		{
    
    
			a[x][y]=i;
			h[x][i]=1;
			l[y][i]=1;
			g[ch(x)][ch(y)][i]=1;
			if(y==9)
				dfs(x+1,1);
			else
				dfs(x,y+1);
			a[x][y]=0;
			h[x][i]=0;
			l[y][i]=0;
			g[ch(x)][ch(y)][i]=0;
		}
}

int main()
{
    
    
	while(cin>>T)
	{
    
    
		if(T=="end")
			return 0;
		for(int i=1;i<=9;i++)
			for(int j=1;j<=9;j++)
			{
    
    
				if(T[(i-1)*9+j-1]>='0'&&T[(i-1)*9+j-1]<='9')
				{
    
    
					a[i][j]=T[(i-1)*9+j-1]-'0';
					h[i][a[i][j]]=1;
					l[j][a[i][j]]=1;
					g[ch(i)][ch(j)][a[i][j]]=1;
				}
				else
					a[i][j]=0;
			}
		ok=0;
		dfs(1,1);
		cout<<endl;
		memset(a,0,sizeof(a));
		memset(h,0,sizeof(h));
		memset(l,0,sizeof(l));
		memset(g,0,sizeof(g));
	}
}

Guess you like

Origin blog.csdn.net/SSL_guyixin/article/details/112117827