首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。