Main topic:
Nine problem, also some people called Sudoku problem
A grid of 9 rows and 9 columns, subdivided into 9 3*3 sub-grids, requires that only one digit in 1~9 is used in each row, column, and sub-grid, that is, the same number is not allowed in each row, per column, or in each sub-grid.
0 is the pending position, and the others are filled in.
Required to complete the nine and output (if there are multiple results, you only need to output one of them)
If the given nine can not be filled out as required, then output the original input of the nine Gongge
Ideas:
DFS Deep Search
Char map[10][10];/* data store */
BOOL row[10][10];/* Row Existence number */
BOOL col[10][10];/* Column Existence number */
BOOL grid[10][10];/* Lattice existence number */
1 /*poj2676 Sudoku*/2#include <iostream>3#include <cstdio>4#include <cstring>5 using namespacestd;6 7 Charmap[Ten][Ten];8 BOOLrow[Ten][Ten];/*Row Existence number*/9 BOOLcol[Ten][Ten];/*column existence number*/ Ten BOOLgrid[Ten][Ten];/*Lattice existence number*/ One A BOOLDfsintXinty) - { - if(x = =Ten) the return true; - BOOLFlag =false; - if(Map[x][y]-'0') - { + if(Y = =9) -Flag = DFS (x+1,1); + Else{ AFlag = DFS (x, y+1); at } - if(flag) - return true; - Else{ - return false; - } in } - Else{ to for(inti =1; i<=9; i++) + { - if(!row[x][i] &&!col[y][i] &&!grid[3* ((X1)/3) + (Y1)/3+1][i]) the { *Map[x][y] = i+'0'; $Row[x][i] =true;Panax NotoginsengCol[y][i] =true; -grid[3* ((X1)/3) + (Y1)/3+1][i] =true; the + if(Y = =9) AFlag = DFS (x+1,1); the Else{ +Flag = DFS (x, y+1); - } $ if(!flag) $ { -Map[x][y] ='0'; -Row[x][i] =false; theCol[y][i] =false; -grid[3* ((X1)/3) + (Y1)/3+1][i] =false;Wuyi the } - Else{ Wu return true; - } About } $ } - } - return false; - } A + voidjudge () the { -memset (Row,0,sizeof(Row)); $memset (Col,0,sizeof(col)); thememset (Grid,0,sizeof(grid)); the the for(inti =1; i<=9; i++) the { - for(intj =1; j<=9; J + +) in { the if(Map[i][j]! ='0') the { Aboutrow[i][map[i][j]-'0'] =true; thecol[j][map[i][j]-'0'] =true; thegrid[3* ((I-1)/3) + (J-1)/3+1][map[i][j]-'0'] =true; the } + } - } the /*for (int i = 1; i<= 9; i++)Bayi { the For (int j = 1; j<= 9; j + +) the cout<<grid[i][j]; - printf ("\ n"); - } the printf ("\ n"); the */ the } the - voidSolve () the { thememset (Map,0,sizeof(map)); the for(inti =1; i<=9; i++)94 { theGets (Map[i] +1); the } the judge ();98Dfs1,1); About - for(inti =1; i<=9; i++)101Puts (Map[i] +1);102printf"\ n");103 }104 the intMain ()106 {107 intT;108 //freopen ("Test.txt", "R", stdin);109scanf"%d", &t); the GetChar ();111 while(t--) the {113 solve (); the } the return 0; the}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced
Poj 2676 Sudoku[dfs]