Write a program to solve a Sudoku puzzle by filling the empty cells.
Empty cells are indicated by the character ‘.‘
.
You may assume that there will be only one unique solution.
A sudoku puzzle...
...and its solution numbers marked in red.
解:
bool isValid(vector<vector<char>> & board, int x, int y){ for(int i=0; i<board.size(); i++){ if(board[i][y]=='.' || i==x) continue; if(board[x][y]==board[i][y]) return false; } for(int i=0; i<board[0].size(); i++){ if(board[x][i]=='.' || i==y) continue; if(board[x][y]==board[x][i]) return false; } int startx=x/3*3; int starty=y/3*3; for(int i=startx; i<startx+3; i++){ for(int j=starty; j<starty+3; j++){ if(board[i][j]=='.' || i==x || j==y) continue; if(board[i][j]==board[x][y]) return false; } } return true; } bool solveSudo(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]!='.') continue; int k; for(k=1; k<10; k++){ board[i][j]=k+'0'; if(isValid(board, i, j)) { if(solveSudo(board)) return true; } board[i][j]='.'; } return false;//没有任何判断,直接返回false } } return true; } void solveSudoku(vector<vector<char>>& board) { solveSudo(board); }
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/jisuanji_wjfioj/article/details/46883247