Solving Sudoku
Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells is indicated by the character ‘.‘
.
Assume that there would be is only one unique solution.
A Sudoku Puzzle ...
Ideas:
Search Plus pruning.
First set up 3 auxiliary two-dimensional arrays: rows, columns, grids to maintain the current Sudoku State, Rows[i][k] (1<=i, k<=9) indicates whether the row I occupies the number k, the same colums[i][k] indicates whether the column I occupies the number k , Grid[i][k] Indicates whether the first lattice occupies the number k,
It then reads the two-dimensional array for the first time, updating rows, columns, and grids.
Second reading of the two-dimensional array for each '. ' Elements to enumerate the possible values based on rows,columns and grid. If there are no values that can be enumerated, the direct pruning is returned.
The code is as follows:
Runtime: 5 ms
Static intcolumns[9][Ten];Static introws[9][Ten];Static intgrids[9][Ten];intSearchChar*board[9],intStarti,intSTARTJ) { for(inti = Starti; I <9; ++i) { for(intj = i = = Starti? STARTJ:0; J <9; ++j) {if(Board[i][j] = ='.') { for(intK =1; K <=9; ++k) {if(!rows[i][k] &&!columns[j][k] &&!grids[i/3+ j/3*3][k]) {Rows[i][k]=1; COLUMNS[J][K]=1; Grids[i/3+ j/3*3][K] =1; if(Search (board, I, j+1) ==1) {Board[i][j]= k +'0'; return 1; } Rows[i][k]=0; COLUMNS[J][K]=0; Grids[i/3+ j/3*3][K] =0; } } return 0; } } } return 1;}voidSolvesudoku (Char* board[9]) {memset (columns,0,sizeof(columns)); memset (Rows,0,sizeof(rows)); memset (grids,0,sizeof(grids)); for(inti =0; I <9; ++i) { for(intj =0; J <9; ++j) {if(Board[i][j]! ='.') {Rows[i][board[i][j]-'0'] =1; COLUMNS[J][BOARD[I][J]-'0'] =1; intTMP = i/3+ j/3*3; GRIDS[TMP][BOARD[I][J]-'0'] =1; }}} Search (board,0,0);}
Leetcode problem Notoginseng--Sudoku Solver