C++高級搜索算法例題及講解—————Sudoku

題目描述:

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. 

輸入:

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.

輸出:

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.

樣例輸入:

1
103000509
002109400
000704000
300502006
060000050
700803004
000401000
009205800
804000107

樣例輸出:

143628579
572139468
986754231
391542786
468917352
725863914
237481695
619275843
854396127

思路分析:

起這道題就是要你填數獨,而數獨是什麼?

如圖所示,具有9行和9列的方形表被分成9個較小的正方形3x3。在一些單元格中寫入從1到9的十進制數字。其他單元格爲空。目標是用1到9的十進制數字填充空單元格,每個單元格一個數字,這樣在每行,每列和每個標記的3x3子方格中,所有數字從1到9出現。

而這道題的思路也是十分簡單。

用三個標記數組標記每行,每列,每個小方塊所出現的數字的情況。

但是如何判斷此時的數是在那個小方塊裏?

將方塊的行數列數除以三相加(就可以求出數的方塊),但是爲了不溢出,我們要在除三之前減個一,然後再加一。

然後是在DFS中,一列走完了,用if判斷一下就可以了。

代碼實現:

#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
int ma[15][15];
bool he[15][15],li[15][15],p1[15][15];
int t;
bool dfs(int x,int y)
{
	if(x==10)
		return 1;
	bool v=0;
	if(ma[x][y])
	{
		if(y==9)
			v=dfs(x+1,1);
		else
			v=dfs(x,y+1);
		if(v)
			return 1;
		else
			return 0;
	}
	else
	{
		int k=3*((x-1)/3)+(y-1)/3+1;
		for(int i=1;i<=9;i++)
		{
			if(!he[x][i]&&!li[y][i]&&!p1[k][i])
			{
				he[x][i]=1;
				li[y][i]=1;
				p1[k][i]=1;
				ma[x][y]=i;
				if(y<9)
					v=dfs(x,y+1);
				else
					v=dfs(x+1,1);
				if(!v)
				{
					he[x][i]=0;
					li[y][i]=0;
					p1[k][i]=0;
					ma[x][y]=0;
				}
				else
					return 1;
			}
		}
	}
	return 0;
}
int main()
{
	scanf("%d",&t);
	while(t--)
	{
		memset(he,0,sizeof(he));
		memset(li,0,sizeof(li));
		memset(p1,0,sizeof(p1));
		for(int i=1;i<=9;i++)
			for(int j=1;j<=9;j++)
			{
				int k=3*((i-1)/3)+(j-1)/3+1;
				scanf("%1d",&ma[i][j]);
				he[i][ma[i][j]]=1;
				li[j][ma[i][j]]=1;
				p1[k][ma[i][j]]=1;
			}
		dfs(1,1);
		for(int i=1;i<=9;i++)
		{
			for(int j=1;j<=9;j++)
				printf("%d",ma[i][j]);
			printf("\n");
		}
	}	
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章