题目链接: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 '.'.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
这道题的要求是检测数独是否有效,其中空位置用‘.’填充,部分填充的只检测有数字的部分。
这道题比较简单,可以使用3个数组记录每行、每列、每个九宫格出现过的数字,然后遍历数独的数组即可。遇到数字时,检测对应行、对应列以及对应九宫格是否已经出现过该数字,如果出现,返回false;否则,将对应行、对应列以及对应九宫格的该数字位置标记为1。
时间复杂度:O(n2)
空间复杂度:O(n2)
1 class Solution
2 {
3 public:
4 bool isValidSudoku(vector<vector<char> > &board)
5 {
6 int used1[9][9] = {0}, used2[9][9] = {0}, used3[9][9] = {0};
7
8 for(int i = 0; i < board.size(); ++ i)
9 for(int j = 0; j < board[i].size(); ++ j)
10 if(board[i][j] != '.')
11 {
12 int num = board[i][j] - '0' - 1, k = i / 3 * 3 + j / 3;
13 if(used1[i][num] || used2[j][num] || used3[k][num])
14 return false;
15 used1[i][num] = used2[j][num] = used3[k][num] = 1;
16 }
17
18 return true;
19 }
20 };