算法描述:
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
- Each of the digits
1-9
must occur exactly once in each row. - Each of the digits
1-9
must occur exactly once in each column. - Each of the the digits
1-9
must occur exactly once in each of the 93x3
sub-boxes of the grid.
Empty cells are indicated by the character '.'
.
解题思路:采用回溯法,每次尝试一个数字并判断合法性。如果不合法,则返回并恢复棋盘。
void solveSudoku(vector<vector<char>>& board) { if(board.size()==0 || board[0].size()==0) return; solve(board); } bool solve(vector<vector<char>>& board){ for(int i=0; i < board.size(); i++){ for(int j=0; j < board[0].size(); j++){ if(board[i][j]=='.'){ for(char c = '1'; c <= '9'; c++){ if(isValid(board,i,j,c)){ board[i][j] = c; if(solve(board)) return true; board[i][j] = '.'; } } return false; } } } return true; } bool isValid(vector<vector<char>> &board, int row, int col, char c){ for(int i =0; i < 9; i++){ if(board[row][i]!='.' && board[row][i]==c) return false; if(board[i][col]!='.' && board[i][col]==c) return false; if(board[3*(row/3)+i/3][3*(col/3)+i%3]!='.' && board[3*(row/3)+i/3][3*(col/3)+i%3]==c) return false; } return true; }