首页 > 其他 > 详细

leetcode--Valid Sudoku

时间:2014-01-30 11:13:17      阅读:454      评论:0      收藏:0      [点我收藏+]

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

bubuko.com,布布扣

A partially filled sudoku which is valid.

 

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

 

bubuko.com,布布扣
 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 }
bubuko.com,布布扣

leetcode--Valid Sudoku

原文:http://www.cnblogs.com/averillzheng/p/3536466.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!