数独填空 深搜

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.
在这里插入图片描述
Input
The input data will start with the number of the test cases. For each test case, 9 lines follow, corresponding to the rows of the table. On each line a string of exactly 9 decimal digits is given, corresponding to the cells in this line. If a cell is empty it is represented by 0.
Output
For each test case your program should print the solution in the same format as the input data. The empty cells have to be filled according to the rules. If solutions is not unique, then the program may print any one of them.

Sample Input
1
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107

Sample Output
143628579
572139468
986754231
391542786
468917352
725863914
237481695
619275843
854396127
大体意思就是说给你一个数字化的数组,让你根据数独规则来填完这个数组,注意这里并没有数独里斜着一行不能重复的规则,这里的深搜需要三个标记数组,一个用来记录这一行出没出现过这个数字,一个用来记录这一列有没有出现这个数字,最后一个用来记录所在方块内有没有出现过,从每一行的最左边开始,搜到最右边,再跳转到下一行,当到达第九行时表示搜索结束,输出即可
AC代码:

#include<iostream>
#include<stdio.h>
#include<memory.h>
using namespace std;
int Map[10][10];
int vis1[10][10];//行 
int vis2[10][10];//列
int vis3[10][10];//记录所在小方块出没出现过
int flag;
void dfs(int x,int y)
{	
	if(x==9)
	{
		flag=1;
		for(int i=0;i<9;i++)
		{
			for(int j=0;j<9;j++)
			{
				printf("%d",Map[i][j]);
			}
			printf("\n");
		}
	}
	if(flag==1) return;
	if(Map[x][y])
	{
		if(y==8)dfs(x+1,0);
		else dfs(x,y+1);
	}
	else
	{
		for(int num=1;num<10;num++)
		{
			int k = 3*(x/3)+y/3;
			if(vis1[x][num]!=1&&vis2[y][num]!=1&&vis3[k][num]!=1)
			{
				Map[x][y]=num;
				vis1[x][num]=1;
				vis2[y][num]=1;
				vis3[k][num]=1;
				if(y==8)dfs(x+1,0);
				else dfs(x,y+1);
				Map[x][y]=0;//如果返回了说明这个数不适用于这个情况,要继续搜素
				vis1[x][num]=0;
				vis2[y][num]=0;
				vis3[k][num]=0;
			}
		}
	}
}
int main()
{
	int i,j,n;
	scanf("%d",&n);
	getchar();
	while(n--)
	{
		memset(vis1,0,sizeof(vis1));
		memset(vis2,0,sizeof(vis2));
		memset(vis3,0,sizeof(vis3));
		for(i=0;i<9;i++)
		{
			for(j=0;j<9;j++)
			{
				char temp;
				scanf("%c",&temp);
				Map[i][j]=temp-'0';
				if(Map[i][j])
				{
					vis1[i][temp-'0']=1;
					vis2[j][temp-'0']=1;
					int k = 3*(i/3)+j/3;
					vis3[k][temp-'0']=1;
				}
			}
			getchar();
		}
		flag=0;
		dfs(0,0);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43849505/article/details/86571823