36. Valid Sudoku

36. Valid Sudoku

   class Solution {
public boolean isValidSudoku(char[][] board) {
for (int i = 0; i < board.length; i++) { HashSet dataInRow = new HashSet();
for (int j = 0; j < board.length; j++) {
if (board[i][j] != '.')
if (dataInRow.contains(board[i][j]))
return false;
else
dataInRow.add(board[i][j]);
}
} for (int j = 0; j < board.length; j++) {
        HashSet<Character> dataInRow = new HashSet<Character>();
        for (int i = 0; i < board.length; i++) {
            if (board[i][j] != '.')
                if (dataInRow.contains(board[i][j]))
                    return false;
                else
                    dataInRow.add(board[i][j]);
        }
    }
    for (int i = 0; i < board.length; i = i + 3) {
        for (int j = 0; j < board.length; j = j + 3) {
            if (!checkValid(i, j, board))
                return false;
        }
    }

    return true;
}

private boolean checkValid(int a, int b, char[][] board) {
    HashSet<Character> dataInSquare = new HashSet<Character>();
    int aEnd = a + 3;
    int bEnd = b + 3;
    for (int i = a; i < aEnd; i++) {
        for (int j = b; j < bEnd; j++) {
            if (board[i][j] != '.')
                if (dataInSquare.contains(board[i][j]))
                    return false;
                else
                    dataInSquare.add(board[i][j]);
        }
    }
    return true;
}

}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s