原题链接在这里:https://leetcode.com/problems/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.
这道题基本没有什么快速方法,唯一就是brute force.
首先在检查前,给出的board是否符合基本要求,是否为空。
然后检查每一行每一列,但问题的关键是如何检查sub box. 这里设值index 0-8 box, loop row with box/3*3 - box/3*3+3, loop column with box%3*3 - box%3*3+3.
这个小trick要记住。
这里选用HashSet 作为检验是否有重复的data structure, 但切记:在outer loop 开始时 要clear HashSet.
AC Java
public class Solution {
public boolean isValidSudoku(char[][] board) {
if(board == null || board.length != 9 || board[0].length != 9){
return false;
}
HashSet hs = new HashSet();
//Check each rows
for(int i = 0;i<board.length;i++){
hs.clear();
for(int j = 0; j<board[0].length; j++){
if(board[i][j] != '.'){
if(!hs.contains(board[i][j])){
hs.add(board[i][j]);
}
else{
return false;
}
}
}
}
//check each column
for(int j = 0;j<board[0].length;j++){
hs.clear();
for(int i = 0; i<board.length; i++){
if(board[i][j] != '.'){
if(!hs.contains(board[i][j])){
hs.add(board[i][j]);
}
else{
return false;
}
}
}
}
//check each subBox
for(int box = 0;box<9;box++){
hs.clear();
for(int i = box/3*3; i<box/3*3+3; i++)
for(int j = box%3*3;j<box%3*3+3;j++){
if(board[i][j] != '.'){
if(!hs.contains(board[i][j])){
hs.add(board[i][j]);
}
else{
return false;
}
}
}
}
return true;
}
}
可以看到,time complexity = O(n^2).