POJ - 2676:Sudoku

Sudoku

来源:POJ

标签:图论->深度优先搜索

参考资料:

相似题目:

题目

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.
POJ - 2676:Sudoku_第1张图片

输入

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

题目大意

做数独游戏。数独游戏规则如下:
1.每一行的方格中填入1~9,数字不能重复;
2.每一列的方格中填入1~9,数字不能重复;
3.顺序排列的3*3的方块中的数字不能重复。

解题思路

深度优先搜索,详见代码。

参考代码

#include
#include
int sudoku[10][10];//存放数独,数组从1开始 
int row_has[10][10];//row_has[i][v]:第i行是否已存在值v。数组从1开始 
int col_has[10][10];//col_has[j][v]:第j列是否已存在值v。数组从1开始 
int square_has[9][10];//3*3的方块中检测,square_has[i][v]:第i个方块中是否已存在v,数组从0开始。 
int ret;
int dfs(int x,int y){
	if(x==10 && y==1){//到达这个状态就表示全部填满了 
		return 1;
	}
	if(sudoku[x][y]!=0){//如果此处值不为0,就不应该在此处填 
		return dfs(y==9?x+1:x, y==9?1:y+1);//换下一个位置,注意当y=9时,要换下一行了
	}
	
	for(int v=1;v<=9;v++){
		if(row_has[x][v]==0 && col_has[y][v]==0 && square_has[(x-1)/3*3+(y-1)/3][v]==0){
			sudoku[x][y]=v;
			row_has[x][v]=1;
			col_has[y][v]=1;
			square_has[(x-1)/3*3+(y-1)/3][v]=1;
			ret=dfs(y==9?x+1:x, y==9?1:y+1);
			if(ret==0){
				sudoku[x][y]=0;
				row_has[x][v]=0;
				col_has[y][v]=0;
				square_has[(x-1)/3*3+(y-1)/3][v]=0;
			}else{
				return 1;
			}
		}
	}
	return 0;
}


int main(){
	int T;
	scanf("%d",&T);
	while(T--){
		memset(row_has,0,sizeof(row_has));
		memset(col_has,0,sizeof(col_has));
		memset(square_has,0,sizeof(square_has));
		for(int i=1;i<=9;i++){
			for(int j=1;j<=9;j++){
				scanf("%1d",&sudoku[i][j]);
				row_has[i][sudoku[i][j]]=1;
				col_has[j][sudoku[i][j]]=1;
				square_has[(i-1)/3*3+(j-1)/3][sudoku[i][j]]=1;
			}
		}
		dfs(1,1);//从1,1位置开始深搜,然后依次从左到右,从上到下。
		for(int i=1;i<=9;i++){
			for(int j=1;j<=9;j++){
				printf("%d",sudoku[i][j]);
			}
			printf("\n");
		}
	}
}

你可能感兴趣的:(【记录】算法题解)