2014年4月12日 星期六

[LeetCode] Valid Sudoku

Problem:
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:O(n^2)
public class Solution {
   public boolean isValidSudoku(char[][] board){
      boolean [][] rows=new boolean[9][9];
      boolean [][] cols=new boolean[9][9];
      boolean [][] blocks=new boolean[9][9];

      for (int i = 0; i < 9; i++) {  
         for (int j = 0; j < 9; j++) {
            int c = board[i][j] - '1';
            if (board[i][j] == '.') 
               continue;  
            int index = i - i % 3+ j / 3; 
            if (rows[i][c] || cols[j][c] || blocks[index][c])  
               return false;  
            rows[i][c] = cols[j][c] = blocks[index][c] = true;  
         }  
      }  
      return true;  
   }
}
Key Concept: use i,j to get it's block index

沒有留言:

張貼留言