Wednesday, March 4, 2015

36. Valid Sudoku Leetcode Java

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:
Solution is straightforward, check each char in the board and see if they obey the sudoku's rule. I use three boolean arrays to track all the visited numbers in rows, columns and blocks. 
 public boolean isValidSudoku(char[][] board) {  
     if(board==null || board.length==0 || board[0].length==0) return false;  
     boolean[][] row=new boolean[9][9];  
     boolean[][] column= new boolean[9][9];  
     boolean[][] block= new boolean[9][9];  
     for(int i=0;i<board.length;i++){  
       for(int j=0;j<board[0].length;j++){  
         if(board[i][j]<='9' && board[i][j]>='1'){  
         int num=board[i][j]-'1';  
         int bl=(i/3)*3+j/3;  
         if(row[i][num] || column[j][num] || block[bl][num]) return false;  
         row[i][num]=column[j][num]=block[bl][num]=true;  
         }  
       }  
     }  
     return true;  
   }  

No comments:

Post a Comment