poj-2676 数独 ——DFS

 

Sudoku

Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 22993   Accepted: 10791   Special Judge

Description

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

 

题意:将数字1到9,填入9x9矩阵中的小方格,使得矩阵中的每行,每列,每个3x3的小格子内,9个数字都会出现。

 

直接暴搜DFS::

#include
#include
#include
#include
using namespace std;
#define Max 50
int mp[10][10];
int line[Max][Max];//line[i][num]:第i行有数字num
int row[Max][Max];//row[i][num]:第i列有数字num
int MM[Max][Max];//第i块有数字num
int a[100][2];
int k;
int flag;
void DFS(int index)
{
	if (index == -1)
	{
		for (int i = 0; i < 9; i++)
		{
			for (int j = 0; j < 9; j++)
			{
				cout << mp[i][j];
			}
			cout << endl;
		}
		flag = 0;
		return;
	}
	if(flag==1)
	for (int i = 1; i <= 9; i++)
	{
		if (row[a[index][0]][i] == 0 && line[a[index][1]][i] == 0 && MM[(a[index][0] / 3)*3+a[index][1] / 3][i] == 0)
		{
			row[a[index][0]][i] = 1;
			line[a[index][1]][i] = 1;
			MM[(a[index][0] / 3)*3+a[index][1] / 3][i] = 1;
			mp[a[index][0]][a[index][1]] = i;
			DFS(index - 1);
			row[a[index][0]][i] = 0;
			line[a[index][1]][i] = 0;
			MM[(a[index][0] / 3)*3+a[index][1] / 3][i] = 0;
		}
	}
}
int main()
{
	int t;
	string str;
	cin >> t;
	while (t--)
	{
		flag = 1;
		k = 0;
		cin.get();
		for (int i = 0; i < 9; i++)
		{
			cin >> str;
			for (int j = 0; j < 9; j++)
			{
				mp[i][j] = str[j] - '0';
			}
		}
		for (int i = 0; i < 9; i++)
		{
			for (int j = 0; j < 9; j++)
			{
				if (mp[i][j])
				{
					row[i][mp[i][j]] = 1;
					line[j][mp[i][j]] = 1;
					MM[(i / 3) * 3 + j / 3][mp[i][j]] = 1;
				}
				else
				{
					a[k][0] = i;
					a[k++][1] = j;
				}
			}
		}
		DFS(k-1);//从后面搜快一点,数据问题
	}
	return 0;
}

 

你可能感兴趣的:(算法)