Valid Sudoku

Determine if a Sudoku is valid, according to Sudoku Puzzles Rules.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

Solution:

public class Solution {
    public boolean isValidSudoku(char[][] board) {

        for(int i=0; i<board.length; i++){
            int[] t = new int[9];
            for(int j=0; j<board.length; j++){
                char ch = board[i][j];
                if(ch=='.') continue;
                if(t[ch-'1']==1){
                    return false;
                } else {
                    t[ch-'1']=1;
                }
            }
        }
        
        for(int j=0; j<board.length; j++){
            int[] t = new int[9];
            for(int i=0; i<board.length; i++){
                char ch = board[i][j];
                if(ch=='.') continue;
                if(t[ch-'1']==1){
                    return false;
                } else {
                    t[ch-'1']=1;
                }
            }
        }
        
        for(int i=0; i<3; i++){
            for(int j=0; j<3; j++){
                int[] t = new int[9];
                for(int r=0; r<3; r++){
                    for(int c=0; c<3; c++){
                        char ch = board[i*3+r][j*3+c];
                        if(ch=='.') continue;
                        if(t[ch-'1']==1){
                            return false;
                        } else {
                            t[ch-'1']=1;
                        }
                    }
                }
            }
        }
        
        return true;
    }
}
comments powered by Disqus