36、有效的数独
1)题目描述
请你判断一个 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 存在, 因此这个数独是无效的。
提示:
board.length == 9
board[i].length == 9
board[i][j]
是一位数字(1-9
)或者'.'
2)分析
哈希表一次遍历。可以使用哈希表记录每一行、每一列和每一个小九宫格中,每个数字出现的次数。只需要遍历数独一次,在遍历的过程中更新哈希表中的计数,并判断是否满足有效的数独的条件即可。
对于给i
行j
列的元素,其行位置为i
,列位置为j
,小方格位置i/3,j/3
。设定三个数组分别r[9][9]、l[9][9]、box[3][3][9]
记录行、列、小方格中1-9
九个数字出现的次数。r
和l
都是二位是数组,有九行,每一行九个元素,分别记录数独表中每一行里面1-9
的出现次数和数独表中每一列里面1-9
的出现次数,box
是三维数组,前两维表示小方格在数独表中的坐标(三行三列),第三维记录每个小方格中1-9
出现的次数。
遍历过程中,board[i][j]
–>r[i][value]++,l[j][value]++,box[i/3][j/3][value]++
,其中value
是board[i][j]
对应的数字。同时判断自增之后的r[i][value]++,l[j][value]++,box[i/3][j/3][value]++
若大于一,则返回false
。若遍历结束都没有出现大于一,返回true
。
3)C++
代码
class Solution {
public:
bool isValidSudoku(vector<vector<char>>& board) {
int r[9][9];
int l[9][9];
int box[3][3][9];
memset(r,0,sizeof(r));
memset(l,0,sizeof(l));
memset(box,0,sizeof(box));
for(int i=0;i<9;i++){
for(int j=0;j<9;j++){
char ch=board[i][j];
if(ch!='.'){
int value=ch-'0'-1;
r[i][value]++;
l[j][value]++;
box[i/3][j/3][value]++;
if(r[i][value]>1||l[j][value]>1||box[i/3][j/3][value]>1)
return false;
}
}
}
return true;
}
};