2014年5月13日星期二

Loop Solution - Valid Sudoku

The idea is to loop each vertical and horizontal and each 3*3 qualified square, by verify each of those units are unique numbers. A set helps.

The key is to not afraid, just analyze what the problem is, what is the way to resolve such a problem! Loop is necessary, make the decision that loop!

public class Solution {
    public boolean isValidSudoku(char[][] board) {
        boolean isValid = true;
//Horizontally
for(int i = 0; i < 9; i++){
Set<Integer> processH = new HashSet<Integer>();
for(int j = 0; j < 9; j++){
if(board[i][j] != '.' && !processH.add(board[i][j] - '0')){
isValid = false;
}
}
}
//Vertically
for(int j = 0; j < 9; j++){
Set<Integer> processV = new HashSet<Integer>();
for(int i = 0; i < 9; i++){
if(board[i][j] != '.' && !processV.add(board[i][j] - '0')){
isValid = false;
}
}
}
//each 3*3
for(int i = 0; i < 3; i++){
for(int j = 0; j < 3; j++){
Set<Integer> processS = new HashSet<Integer>();
for(int m = 0; m < 3; m++){
for(int n = 0; n < 3; n++){
if(board[i * 3 + m][j * 3 + n] != '.' && !processS.add(board[i * 3 + m][j * 3 + n] - '0')){
isValid = false;
}
}
}
}
}
return isValid;
    }
}

没有评论: