37. Sudoku Solver **
生活随笔
收集整理的這篇文章主要介紹了
37. Sudoku Solver **
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
description:
數獨
Note:
Example:
Example 1:Input: [["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"] ] Output: trueExample 2:Input: [["8","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"] ] Output: false Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.answer:
class Solution { public:void solveSudoku(vector<vector<char>>& board) {if (board.empty() || board.size() != 9 || board[0].size() != 9) return;solveDFS(board, 0, 0); //從陣列的左上角開始逐行逐列的遞歸填入檢查}bool solveDFS(vector<vector<char>> &board, int i, int j) {if (i == 9) return true; // 如果行號到了9, 就證明已經全部遍歷完畢if (j >= 9) return solveDFS(board, i + 1, 0); // 如果列號大于等于9了,就證明這一行已經ok了,可以進行下一行的遞歸了。if (board[i][j] == '.') { // 如果是需要填入的空,那就從1到9挨個試,看看哪個填入是合法的for (int k = 1; k <= 9; k++){board[i][j] = (char)(k + '0');if (isValid(board, i, j)) { // 如果是合法的,就繼續遞歸,跳出遞歸之后就結束了也,這里必須要寫return ,這樣才能跳出循環,同時滿足函數返回值類型if (solveDFS(board, i, j + 1)) return true;}board[i][j] = '.'; // 這個是只有九個數都試過了但是都不行,就恢復原狀,然后就跳到最后那個 return false 上去了,這樣它前面一列那個數就相當于要換個k重新試試,這樣不斷往前改,總是能保證當前數之前填過的數都是正確的。}} else {return solveDFS(board, i, j + 1); // 如果不是需要去填的空,就跳過現在這個數繼續遞歸,這里一定要寫return}return false; }bool isValid(vector<vector<char>> &board, int i, int j) {for (int col = 0; col < 9; ++col) {if (col != j && board[i][j] == board[i][col]) return false;}for (int row = 0; row < 9; ++row) {if (row != i && board[i][j] == board[row][j]) return false;}for (int row = i/3*3; row < i/3*3 + 3; ++row) {for (int col = j/3*3; col < j/3*3 + 3; ++col) {if ((row != i || col != j) && board[i][j] == board[row][col]) return false; //這里是 || 只要行或者列任意一個數不一樣就要比一下}}return true;} };relative point get√:
hint :
轉載于:https://www.cnblogs.com/forPrometheus-jun/p/11123306.html
總結
以上是生活随笔為你收集整理的37. Sudoku Solver **的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php - 冒泡排序
- 下一篇: 如何证明你的能力?