Sunday, April 20, 2014

Leetcode: 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.

Solution:


public class Solution {
    public boolean isValidSudoku(char[][] board) {
        
        for(int i=0; i<9; i++)
        {
            boolean[] row = new boolean[9];
            boolean[] col = new boolean[9];
            boolean[] square = new boolean[9];
            for(int j=0; j<9; j++)
            {
                if(board[i][j] != '.')    
                {
                    if(Character.isDigit(board[i][j]) && !row[board[i][j]-'1']  )
                        row[board[i][j]-'1'] = true;
                    else 
                        return false;
                }
                
                if(board[j][i] != '.')    
                {
                    if(Character.isDigit(board[j][i]) && !col[board[j][i]-'1']  )
                        col[board[j][i]-'1'] = true;
                    else 
                        return false;
                }
                int colS = (i%3)*3+ j%3;
                int rowS = (i/3)*3 + j/3;
                if(board[rowS][colS] != '.')    
                {
                    if(Character.isDigit(board[rowS][colS]) && !square[board[rowS][colS]-'1'] )
                        square[board[rowS][colS]-'1'] = true;
                    else 
                        return false;
                }
            }
        }
        return true;
    }
}

No comments :

Post a Comment