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 ‘.‘.

leetcode--Valid Sudoku

A partially filled sudoku which is valid.

 

Here is a brute force method. I do not whether there is an other smart method.

 

leetcode--Valid Sudoku
 1 public class Solution{
 2     public boolean isValidSudoku(char[][] board) {
 3         boolean isValid = true;
 4         HashSet<Character> column = new HashSet<Character>();
 5         HashSet<Character> row = new HashSet<Character>();
 6         for(int i = 0; i < 9; ++i){
 7             //clear the set, before we insert into a new row or column
 8             column.clear();
 9             row.clear();
10             for(int j = 0; j < 9; ++j){
11                 if(board[i][j] != ‘.‘)
12                     isValid = isValid && row.add(board[i][j]);
13                 if(board[j][i] != ‘.‘)
14                     isValid = isValid && column.add(board[j][i]); 
15                 if(!isValid)
16                     break;
17             }
18             if(!isValid)
19                 break;
20         }
21         if(isValid){
22             HashSet<Character> square = new HashSet<Character>();
23             int i = 0;
24             while(i < 9){
25                 int j = 0;
26                 while(j < 9){
27                     square.clear();
28                     for(int ii = 0; ii < 3; ++ii){
29                         for(int jj = 0; jj < 3; ++jj){
30                             if(board[i +ii][j + jj] != ‘.‘)
31                                 isValid = square.add(board[i +ii][j + jj]); 
32                             if(!isValid)
33                                 return false;
34                         }
35                     }
36                     j += 3;
37                 }
38                 i += 3;
39             }
40         }
41         return isValid;
42     }
43 }
leetcode--Valid Sudoku

leetcode--Valid Sudoku

上一篇:leetcode--First Missing Positive


下一篇:uva 10319(2-SAT)