poj-2676 Sudoku

Posted euzmin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj-2676 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.
技术分享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

依旧是经典的数独问题,上次我写过一个4*4的,这次是9*9。
这题里学到一个技巧分块方面的技巧(可怜我还是一点一点判断的)
这个问题太经典了,就不多说了,附代码:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
const int M = 12;
char st[M][M];
int map[M][M];
int col[M][M];
int row[M][M];
int bl[M][M];
int f=0;
int dfs(int x,int y){
	if(y==10) 
	return 1;
	f=0;
	if(map[x][y]){
		if(x<9) f=dfs(x+1,y);
		else     f=dfs(1,y+1);
		if(f) return 1;
		else     return 0;
	}
	else{
		int k=3*((x-1)/3)+(y-1)/3+1;  
		
		for(int i=1;i<=9;i++){
			if(!col[y][i]&&!row[x][i]&&!bl[k][i]){
				map[x][y]=i;
				col[y][i]=1;
				row[x][i]=1;
				bl[k][i]=1;
				if(x<9) f=dfs(x+1,y);
				else     f=dfs(1,y+1);
				if(f) return 1;
				else{
					map[x][y]=0;
					row[x][i]=0;
					col[y][i]=0;
					bl[k][i]=0;
				}
			}
		}
	}
	return 0;	
}
	
int main(){
	int t;
	cin>>t;
	while(t--){
		 memset(row,false,sizeof(row));
        memset(col,false,sizeof(col));
        memset(bl,false,sizeof(bl));

		f=0;
		for(int i=1;i<=9;i++){
			for(int j=1;j<=9;j++){
				cin>>st[i][j];
				map[i][j]=st[i][j]-‘0‘;
			
			if(map[i][j])
                {
                    int k=3*((i-1)/3)+(j-1)/3+1;  //分块技巧
                    row[i][ map[i][j] ]=1;
                    col[j][ map[i][j] ]=1;
                    bl[k][ map[i][j] ]=1;
                }
			}
		}
		dfs(1,1);
		for(int i=1;i<=9;i++){
			for(int k=1;k<=9;k++){
				cout<<map[i][k];
			}
			cout<<endl;
		}
	}
	return 0;
}
		
	 

  







以上是关于poj-2676 Sudoku的主要内容,如果未能解决你的问题,请参考以下文章

POJ2676 Sudoku - DFS

poj2676 Sudoku(DFS)

POJ2676 Sudoku

poj2676 Sudoku

poj-2676 Sudoku

POJ2676 Sudoku