首页 > 代码库 > 037. Sudoku Solver

037. Sudoku Solver

 1 class Solution { 2 public: 3     void solveSudoku(vector<vector<char>>& board) { 4         Sudoku(board); 5     } 6 private: 7     bool Sudoku(vector<vector<char>>& board) 8     { 9         for (int i = 0; i < 9; ++i) {10             for (int j = 0; j < 9; ++j) {11                 if (board[i][j] == .) {12                     for (int k = 0; k < 9; ++k) {13                         board[i][j] = 1 + k;14                         if (isValid(board, i, j) && Sudoku(board)) return true;15                         board[i][j] = .;16                     }17                     return false;18                 }19             }20         }21         return true;22     }23     bool isValid(vector<vector<char>>& board, int i, int j)24     {25         for (int index = 0; index < 9; ++index) {26             if (index != j && board[i][index] == board[i][j]) return false;27         }28         for (int index = 0; index < 9; ++index) {29             if (index != i && board[index][j] == board[i][j]) return false;30         }31         for (int row = 3 * (i / 3); row < 3 * (i / 3) + 3; ++row) {32             for (int col = 3 * (j / 3); col < 3 * (j / 3) + 3; ++col) {33                 if ((row != i || col != j) && board[row][col] == board[i][j]) return false;34             }35         }36         return true;37     }38 };

 

037. Sudoku Solver