Problem Description:
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 ...
... and its solution numbers marked in red.
Basic idea:
Search by backtracking.
Code:
BOOL Sudoku (int row, int col, int num, vector<vector<char> >& board) {//c++ if (num = = 81) return true; int nextcol,nextrow; if (col = = 8) {nextcol = 0; NextRow = row+1; }else{nextcol = col+1; NextRow = row; } if (Board[row][col]! = '. ') {num++; BOOL suc; Return Sudoku (Nextrow,nextcol,num,board); } for (int i = 1; I <=9; i++) {bool isfilled = Fillcell (Row,col,i,board); BOOL suc; if (isfilled) {Board[row][col] = i + ' 0 '; num++; suc = Sudoku (Nextrow,nextcol,num,board); if (suc = = true) return true; Board[row][col] = '. '; num--; }} return false; } bool Fillcell (int row, int col, int value, vector<vector<char> >& board) {Char ch = value + ' 0 '; for (int i =0; i < 9; i++) {if (board[row][i] = = ch) return false; if (board[i][col] = = ch) return false; } int tmprow = row/3*3; int tmpcol = col/3*3; for (int i = Tmprow, i < tmprow+3; i++) for (int j = Tmpcol; j<tmpcol+3; j + +)//error if (board[i][j] = = ch) return false; return true; } void Solvesudoku (Vector<vector<char> > &board) {sudoku (0,0,0,board); }
[Leetcode] Sudoku Solver