[LettCode]49. Valid Sudoku有效数独
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
Subscribe to see which companies asked this question
解法1:分别判断每行,每列,每个3X3块中是否存在相同数字,时间复杂度O(n^2),空间复杂度O(n)。
class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { if(board.empty() || board[0].empty()) return false; int n = board.size(); vector<int> row(9, 0); vector<int> col(9, 0); for(int i = 0; i < n; ++i) { row.assign(9, 0); col.assign(9, 0); for(int j = 0; j < n; ++j) { if(board[i][j] != '.') { if(row[board[i][j] - '1'] == 1) return false; else ++row[board[i][j] - '1']; } if(board[j][i] != '.') { if(col[board[j][i] - '1'] == 1) return false; else ++col[board[j][i] - '1']; } } } vector<int> c3(9, 0); for(int k = 0; k < n * n / 9; ++k) { c3.assign(9, 0); int starti = k / 3 * 3, startj = k % 3 * 3; for(int col = starti; col < starti + 3; ++col) { for(int row = startj; row < startj + 3; ++row) { if(board[col][row] != '.') { if(c3[board[col][row] - '1'] == 1) return false; else ++c3[board[col][row] - '1']; } } } } return true; } };
在空间复杂度为O(n^2)时可以用一次二层循环解决:
class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { if(board.empty() || board[0].empty()) return false; int n = board.size(); vector<int> row(9, 0); vector<int> col(9, 0); vector< vector<int> > cub(9, vector<int>(9, 0)); for(int i = 0; i < n; ++i) { row.assign(9, 0); col.assign(9, 0); for(int j = 0; j < n; ++j) { if(board[i][j] != '.') { if(row[board[i][j] - '1'] == 1) return false; else ++row[board[i][j] - '1']; int k = i / 3 * 3 + j / 3; if(cub[k][board[i][j] - '1'] == 1) return false; else ++cub[k][board[i][j] - '1']; } if(board[j][i] != '.') { if(col[board[j][i] - '1'] == 1) return false; else ++col[board[j][i] - '1']; } } } return true; } };