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:

 1 public class Solution {
 2     public boolean isValidSudoku(char[][] board) {
 3         int rowNum = board.length;
 4         if (rowNum!=9) return false;
 5         int colNum = board[0].length;
 6         if (colNum!=9) return false;
 7 
 8         for (int i=0;i<rowNum;i++)
 9             if (!checkArea(board,i,0,1,9)) return false;
10   
11         for (int i=0;i<colNum;i++)
12             if (!checkArea(board,0,i,9,1)) return false;
13 
14         int[] index = new int[]{0,3,6};
15         for (int i=0;i<3;i++)
16             for (int j=0;j<3;j++)
17                 if (!checkArea(board,index[i],index[j],3,3)) return false;
18 
19         return true;
20        
21         
22     }
23 
24     public boolean checkArea(char[][] board, int x, int y, int rowNum, int colNum){
25         Set<Integer> set = new HashSet<Integer>();
26         for (int i=0;i<rowNum;i++)
27             for (int j=0;j<colNum;j++)
28                 if (board[x+i][y+j]!='.'){
29                     int val = board[x+i][y+j]-'0';
30                     if (val<0 || val>9) return false;
31                     if (set.contains(val))
32                         return false;
33                     else set.add(val);
34                 }
35 
36         return true;
37 
38     }
39                 
40 }

 

posted @ 2014-11-29 07:30  LiBlog  阅读(141)  评论(0编辑  收藏  举报