码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode: Valid Sudoku 解题报告

时间:2014-11-01 20:31:15      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   io   color   os   ar   使用   

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

bubuko.com,布布扣

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:

使用HashSet 行列,9块分别检查。

bubuko.com,布布扣
 1 public class Solution {
 2     public boolean isValidSudoku(char[][] board) {
 3         if (board == null || board.length != 9 ||
 4             board[0].length != 9) {
 5             return false;
 6         }
 7         
 8         HashSet<Character> set = new HashSet<Character>();
 9         
10         // check the rows.
11         for (int i = 0; i < 9; i++) {
12             // clear the set at every row.
13             set.clear();
14             for (int j = 0; j < 9; j++) {
15                 if (!isValidChar(board[i][j], set)) {
16                     return false;
17                 }
18             }
19         }
20         
21         // check the columns.
22         for (int i = 0; i < 9; i++) {
23             // clear the set at every column.
24             set.clear();
25             for (int j = 0; j < 9; j++) {
26                 if (!isValidChar(board[j][i], set)) {
27                     return false;
28                 }
29             }
30         }
31         
32         // check the blocks.
33         for (int i = 0; i < 9; i+=3) {
34             for (int j = 0; j < 9; j+=3) {
35                 // clear the set at every block.
36                 set.clear();
37                 for (int k = 0; k < 9; k++) {
38                     if (!isValidChar(board[i + k / 3][j + k % 3], set)) {
39                         return false;
40                     }    
41                 }
42             }
43         }
44         
45         return true;
46     }
47     
48     public boolean isValidChar(char c, HashSet<Character> set) {
49         if (c == .) {
50             return true;
51         }
52         
53         if (c < 0 || c > 9) {
54             return false;
55         }
56         
57         // Check if the character exit in the hashset.
58         if (set.contains(c)) {
59             return false;
60         }
61         
62         set.add(c);
63         
64         return true;
65     }
66 }
View Code

主页君的GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/hash/IsValidSudoku.java

 

ref: http://www.ninechapter.com/solutions/valid-sudoku/

LeetCode: Valid Sudoku 解题报告

标签:des   style   blog   http   io   color   os   ar   使用   

原文地址:http://www.cnblogs.com/yuzhangcmu/p/4067608.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!