leetcode-36. 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 ‘.’.
一开始没明白题目的意思,按照讨论的意思来看只要判断一下每一行,每一列和每一个3*3小方格是不是有重复的数就行,其实这样做似乎并不能保证一定有解法。后来自己写的时候发现还是很麻烦的,尤其是最后3*3的小方格比较难判断。要是让我做的话我只有建9个hashset之类的了。后来在讨论区看到一个非常漂亮的答案。
这个答案的基本思路就是虽然也是迭代i和j但是对于每个hashset中的i和j的意义都不一样。这样就可以通过9*3个hashSet来完成所有的验证任务,虽然从工程上说确实有点不太明确,但是我觉得这个程序写的非常简洁,还是非常值得借鉴的。
public class Solution {
public boolean isValidSudoku(char[][] board) {
for(int i = 0 ; i < board.length ; i++){
HashSet<Character> row = new HashSet<Character>();
HashSet<Character> col = new HashSet<Character>();
HashSet<Character> cub = new HashSet<Character>();
for(int j = 0 ; j < board[0].length ; j++){
if(board[i][j]!='.' && !row.add(board[i][j])) return false;
if(board[j][i]!='.' && !col.add(board[j][i])) return false;
int x = 3*(i/3);
int y = 3*(i%3);
if(board[x+j/3][y+j%3]!='.' && !cub.add(board[x+j/3][y+j%3]))return false;
}
}
return true;
}
}