As expected, I still met this topic, haha, since so predestined, then how can we not solve this problem? Sudoku Problem Solving, I thought about this problem last time, the general idea is to use backtracking, is to fill the vacancy and then test whether the value is legitimate, step by step recursively, encountered illegal to go back to the problem position, and then modify the value, and then test, so there are two results 1. Or the last success 2. Either a location 1~9 Could not satisfy test instructions's words, and then quit directly.
I think this topic, first of all to understand the idea of solving problems, I think of the idea but the code is still some problems, so draw on others, the final code as follows, or is a violent search ...
Class Solution {Public:void Solvesudoku (vector<vector<char>>& board) {/* return type void not is very accurate, assuming that the Sudoku has no solution, then we do not know, in the end is wrong or find the solution. Sudoku solution, eventually encountered, can not be avoided, then we have to overcome it, this type of problem is "backtracking" representative */BOOL ret = _solvesudoku (board); if (ret = = true) {cout<< "Find solve" <<endl; } else {cout<< "No Solve" <<endl; }} bool _solvesudoku (vector<vector<char>>& board) {for (int i = 0; i < 9; ++i) {for (int j = 0; J < 9; ++j) {if (board[i][j] = = '. ') {for (int k = 1; k <= 9; ++k) {board[i][j] = ' 0 ' + K; if (Isvild (board,i,j) && _solvesudoku (board)) {//success is returned return true; }//Failed to reset the position to the nextTest values, but first to restore the original value, because we are using board "reference", so we can not skip directly over board[i][j] = '. '; }//1~9 is not satisfied, the failure return false; }}}/* Go here to illustrate some of the problems: 1. Success, do not need to do anything in 2.board '. ', so that it does not enter the IF loop, supposedly This time need to judge again whether board is a positive solution, but there is no judgment is not wrong ... */return true; } bool Isvild (vector<vector<char>> &board, int x,int y) {//Landscape for (int i = 0; I &l T 9; ++i) {if (i! = y && board[x][i] = = Board[x][y]) {//recurring, illegal return fals E }}//portrait for (int i = 0; i < 9; ++i) {if (I! = x && board[i][y] = = board[ X][y]) {return false; }}//Only check the elements in the palace where X and Y are located can be int wid = * * (X/3); x start position int hig = (Y/3); Y start position for (int i = wid; I < WID + 3; ++i) { for (int j = hig; J < hig + 3; ++j) {if (i!=x && j!=y && board[i][j] = = Boa Rd[x][y]) {return false; }}}//Success return true; }};
The results are as follows:
Written question 50. Leetcode OJ (37)