My code:
import java.util.HashSet;
public class Solution {
public boolean isValidSudoku(char[][] board) {
if (board == null || board.length == 0 || board[0].length == 0)
return false;
HashSet<Character> hs = new HashSet<Character>();
boolean isValid = true;
/** deal with row */
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
if (board[i][j] == '.')
continue;
else if (!hs.contains(board[i][j]))
hs.add(board[i][j]);
else if (hs.contains(board[i][j])) {
return false;
}
}
hs.clear();
}
/** deal with col */
for (int i = 0; i < board[0].length; i++) {
for (int j = 0; j < board.length; j++) {
if (board[j][i] == '.')
continue;
else if (!hs.contains(board[j][i]))
hs.add(board[j][i]);
else if (hs.contains(board[j][i]))
return false;
}
hs.clear();
}
/** deal with unit 3x3 */
for (int i = 0; i < board[0].length; i += 3) {
for (int j = 0; j < board.length; j += 3) {
isValid &= helper(i, j, board);
}
}
return isValid;
}
private boolean helper(int i, int j, char[][] board) {
HashSet<Character> hs = new HashSet<Character>();
for (int m = i; m < i + 3; m++) {
for (int n = j; n < j + 3; n++) {
if (board[m][n] == '.')
continue;
else if (!hs.contains(board[m][n]))
hs.add(board[m][n]);
else if (hs.contains(board[m][n]))
return false;
}
}
return true;
}
public static void main(String[] args) {
Solution test = new Solution();
char[][] board = {"..4...63.".toCharArray(),".........".toCharArray(),"5......9.".toCharArray(),"...56....".toCharArray(),"4.3.....1".toCharArray(),"...7.....".toCharArray(),"...5.....".toCharArray(),".........".toCharArray(),".........".toCharArray()};
System.out.println(test.isValidSudoku(board));
}
}
感觉这道题目就是体力活,一点意思都没有。
有机会得去了解下, HashSet 的工作机制。
还有,遍历一个矩阵的时候,要注意次序,i, j这些细节。
另外,main函数中,是可以直接对 char[][] board 初始化的,用上toCharArray 把string转换成 char array 就行了。
**
总结: HashSet
一个多小时做了三道简单题,还是挺舒服的。。。
昨天不该吹牛的,报应在后面等着呢。。。
今晚有时间打算把 sudo这一块给做了。感觉应该还是 DFS, permutation 的思想。
**
Anyway, Good luck, Richardo!