题目:数独(DFS)

版权声明:本文为博主原创文章,欢迎转载。如有问题,欢迎指正。 https://blog.csdn.net/weixin_42172261/article/details/87888414

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.

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

int sudoku[10][10];
int vis[10][10], col[10][10], row[10][10]; 
int isdone;
void dfs(int i, int j)
{
	if(i == 9) 
	{
		isdone = 1;
		for(int i=0; i<9; i++)
		{
			for(int j=0; j<9; j++)
				cout<<sudoku[i][j];
			cout<<endl;
		}
		return ;
	}
	if (isdone==1)
		return;
	if(sudoku[i][j])
	{
		if(j == 8) dfs(i+1,0);
		else  dfs(i,j+1);
	}
	else
	{
		for(int num=1; num<=9; num++)
		{
			int k = 3*(i/3)+j/3;  
			
			if(!row[i][num] && !col[j][num] && !vis[k][num])
			{
				sudoku[i][j] = num;
				row[i][num] = 1;
			    col[j][num] = 1;
				vis[k][num] = 1; 
				if( j == 8)  dfs(i+1,0);
				else  dfs(i,j+1);
				
				sudoku[i][j] = 0;
				row[i][num] = 0;
			    col[j][num] = 0;
				vis[k][num] = 0; 
				
			}
		}
	}
}
int main()
{
	int t;
	cin>>t;
	while(t--)
	{
		memset(vis,0,sizeof(vis));
		memset(col,0,sizeof(col));
		memset(row,0,sizeof(row));
		
		for(int i=0; i<9; i++)
		{
			char tmp[9];
			cin>>tmp;
			
			for(int j=0; j<9; j++)
			{
				sudoku[i][j] = tmp[j]-'0';
				if(sudoku[i][j])
				{
					int k = 3*(i/3)+j/3;
					row[i][sudoku[i][j]] = 1;
					col[j][sudoku[i][j]] = 1;
					vis[k][sudoku[i][j]] = 1; 
				}
			}
		}
		isdone = false; 
		dfs(0,0);
	}
	return 0;
} 

猜你喜欢

转载自blog.csdn.net/weixin_42172261/article/details/87888414