2015年9月20日星期日

Leetcode 36 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 1: simple loop, note we can combine 3 loop and check together, see below.
 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[] sqr=new boolean[9];  
       for (int j=0; j<9; j++) {  
         //row  
         if (board[i][j]!='.') {  
           if (row[board[i][j]-'1']) return false;  
           else row[board[i][j]-'1']=true;  
         }  
         //col  
         if (board[j][i]!='.') {  
           if (col[board[j][i]-'1']) return false;  
           else col[board[j][i]-'1']=true;  
         }  
         //sqr  
         int r=(i/3)*3+j/3;  
         int c=(i%3)*3+j%3;  
         if (board[r][c]!='.') {  
           if (sqr[board[r][c]-'1']) return false;  
           else sqr[board[r][c]-'1']=true;  
         }  
       }  
     }  
     return true;  
   }  
 }  

没有评论:

发表评论