037. Sudoku Solver
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章