标签:
题目:Sudoku
题意:求解数独。从样例和结果来看应该是简单难度的数独
思路:DFS
设置3个数组,row[i][j] 判断第i行是否放了j数字,col[i][j] 判断第i列是否放了j数字。square[i/3][j/3][x]判断第i/3行第j/3列个宫是否放置了x数字;
#include <iostream> #include <algorithm> #include <stdlib.h> #include <time.h> #include <cmath> #include <cstdio> #include <string> #include <cstring> #include <vector> #include <queue> #include <stack> #include <set> #define c_false ios_base::sync_with_stdio(false); cin.tie(0) #define INF 0x3f3f3f3f #define INFL 0x3f3f3f3f3f3f3f3f #define zero_(x,y) memset(x , y , sizeof(x)) #define zero(x) memset(x , 0 , sizeof(x)) #define MAX(x) memset(x , 0x3f ,sizeof(x)) #define swa(x,y) {LL s;s=x;x=y;y=s;} using namespace std ; #define N 50005 const double PI = acos(-1.0); typedef long long LL ; bool col[10][10], row[10][10], square[5][5][10]; char mapp[10]; int MAP[10][10]; int n; bool dfs(int z){ if(z>=81) return true; int x = z/9; int y = z%9; if(MAP[x][y]) return dfs(z+1); for(int i = 1; i<= 9; i++){ if(!row[x][i] && !col[y][i] && !square[x/3][y/3][i]){ MAP[x][y] = i; row[x][i] = col[y][i] = square[x/3][y/3][i] = 1; if(dfs(z+1)) return true; MAP[x][y] = 0; row[x][i] = col[y][i] = square[x/3][y/3][i] = 0; } } return false; } int main(){ //freopen("in.txt","r",stdin); //freopen("out.txt","w",stdout); scanf("%d", &n); while(n--){ //memset(MAP, 0, sizeof(MAP)); memset(row, false, sizeof(row)); memset(col, false, sizeof(col)); memset(square, false, sizeof(square)); for(int i = 0; i<9; i++){ scanf("%s", mapp); for(int j = 0; j<9; j++){ MAP[i][j] = mapp[j] - ‘0‘; int c = MAP[i][j]; if(MAP[i][j]) { row[i][c] = col[j][c] = square[i/3][j/3][c] = 1; } } } dfs(0); for(int i=0;i<9;i++){ for(int j=0;j<9;j++) printf("%d",MAP[i][j]); printf("\n"); } } return 0; }
标签:
原文地址:http://www.cnblogs.com/yoyo-sincerely/p/5309522.html