判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
输入:
[
[“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
题解:遍历二维数组,利用哈希表存储每一列,每一行,每一个小方格中出现的数字,当存在重复数字时,返回false,否则返回true
class Solution {
public boolean isValidSudoku(char[][] board) {
HashMap<Integer,HashSet<Character>>row=new HashMap<>();
HashMap<Integer,HashSet<Character>>column=new HashMap<>();
HashMap<Integer,HashSet<Character>>grid=new HashMap<>();
int rows= board.length;
int columns=board[0].length;
for(int i=0;i<rows;i++)
for(int k=0;k<columns;k++){
if(board[i][k]=='.')
continue;
HashSet<Character>temp=row.getOrDefault(i,new HashSet<Character>());
if(temp.contains(board[i][k]))
return false;
else{
temp.add(board[i][k]);
row.put(i,temp);
}
temp=column.getOrDefault(i,new HashSet<Character>());
if(temp.contains(board[i][k]))
return false;
else{
temp.add(board[i][k]);
column.put(k,temp);
}
temp=grid.getOrDefault((k/3+3*(i/3)),new HashSet<Character>());
if(temp.contains(board[i][k]))
return false;
else{
temp.add(board[i][k]);
grid.put((k/3+3*(i/3)),temp);
}
}
return true;
}
}