原文链接:数据结构003:有效的数独
题目
请你判断一个
9 x 9
的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。
- 数字
1-9
在每一行只能出现一次。- 数字
1-9
在每一列只能出现一次。- 数字
1-9
在每一个以粗实线分隔的3x3
宫内只能出现一次。(请参考示例图)注意:
- 一个有效的数独(部分已被填充)不一定是可解的。
- 只需要根据以上规则,验证已经填入的数字是否有效即可。
- 空白格用
'.'
表示。示例 1:
输入:board = [["5","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] 输出:true
示例 2:
输入:board = [["8","3",".",".","7",".",".",".","."] ,["6",".",".","1","9","5",".",".","."] ,[".","9","8",".",".",".",".","6","."] ,["8",".",".",".","6",".",".",".","3"] ,["4",".",".","8",".","3",".",".","1"] ,["7",".",".",".","2",".",".",".","6"] ,[".","6",".",".",".",".","2","8","."] ,[".",".",".","4","1","9",".",".","5"] ,[".",".",".",".","8",".",".","7","9"]] 输出:false 解释:除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。 但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。
题解
根据题目的规则,数独需要满足三个规则,针对规则一和二可知,我们在遍历每个元素的时候,需要判断该元素所在行和列中是否出现过,即可判断该元素是否满足规则一和二,因此我们可以针对每一行、每一列出现元素的次数作为校验标准,例如声明两个二维数组 r o w [ 9 ] [ 9 ] row[9][9] row[9][9]和 c o l [ 9 ] [ 9 ] col[9][9] col[9][9]分别代表行和列上面 0 − 9 0-9 0−9出现的次数。例如 r o w [ 1 ] [ 2 ] row[1][2] row[1][2]表示第1行中,出现2的次数, c o l [ 4 ] [ 3 ] col[4][3] col[4][3]表示第4列出现3的次数(都是从第0行/列开始算的)。对于数独数组第 i i i行 j j j列上的数值 n = b o a r d [ i ] [ j ] n=board[i][j] n=board[i][j],首先将 r o w [ i ] [ n ] row[i][n] row[i][n]上对应的值加一,再将 c o l [ j ] [ n ] col[j][n] col[j][n]也加一,然后判断 r o w [ i ] [ n ] row[i][n] row[i][n]和 r o w [ i ] [ n ] row[i][n] row[i][n]的值是否大于1,大于1则表明 i i i行或者 j j j列数字 n n n出现的次数大于1,即不唯一。不满足规则一或者二。
对于规则三,我们可以根据元素 b o a r d [ i ] [ j ] board[i][j] board[i][j]的 i i i和 j j j的索引除以3来进行判断其属于哪个小九宫格,即其对应的小九宫格的索引为 i / 3 i/3 i/3和 j / 3 j/3 j/3。因此我们可构建一个 b o x [ 3 ] [ 3 ] [ 9 ] box[3][3][9] box[3][3][9]的三位数组来记录每个小九宫格中 0 − 9 0-9 0−9出现的次数,例如 b o x [ 1 ] [ 2 ] [ 3 ] box[1][2][3] box[1][2][3]表示第一行第二列的九宫格中出现数字3的次数,我们的思路与 r o w row row和 c o l col col一样,遍历每个元素 n = b o a r d [ i ] [ j ] n=board[i][j] n=board[i][j],并将 b o x [ i / 3 ] [ j / 3 ] [ n ] box[i/3][j/3][n] box[i/3][j/3][n]的值加一,在判断其是否大于1。
通过上面的分析,我们的实现代码如下:
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int row[9][9] = {0};
int col[9][9] = {0};
int box[3][3][9] = {0};
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c = board[i][j];
if (c == '.') continue;
int n = c - '1';
row[i][n]++;
col[j][n]++;
box[i / 3][j / 3][n]++;
if (row[i][n] > 1 || col[j][n] > 1 || box[i / 3][j / 3][n] > 1) {
return false;
}
}
}
return true;
}
};
由于数独共有81个单元格,只需要对每个单元格遍历一次即可,因此其时间复杂度为 O ( 1 ) O(1) O(1)。由于数独的大小固定,因此空间的大小也是固定的,空间复杂度也为 O ( 1 ) O(1) O(1)。