[Leetcode 24] 35 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.

 

Analysis:

Simulation problem, the nice part here is use a same function for three different kinds of test as showed in code.

 

Code:

 1 public class Solution {
 2     public boolean isValidSudoku(char[][] board) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         for (int i=0; i<9; ++i) {//judge row
 6             if (!judge(board, i, 0, 1, 9))
 7                 return false;
 8         }
 9         
10         for (int j=0; j<9; ++j) {//judge column
11             if (!judge(board, 0, j, 9, 1))
12                 return false;
13         }
14         
15         for (int i=0; i<3; ++i) {//judge block
16             for (int j=0; j<3; ++j) {
17                 if (!judge(board, i*3, j*3, 3, 3))
18                     return false;
19             }
20         }
21         
22         return true;
23     }
24     
25     private boolean judge(char[][] board, int r, int c, int rl, int cl) {
26         int[] hashT = {0,0,0,0,0,0,0,0,0};
27         
28         for (int i=r; i<r+rl; ++i) {
29             for (int j=c; j<c+cl; ++j) {
30                 if (board[i][j] != '.') {
31                     int idx = board[i][j]-'0'-1;
32                     
33                     if (hashT[idx] != 0) {
34                         return false;
35                     } else {
36                         hashT[idx] ++;
37                     }
38                 }
39             }
40         }
41         
42         return true;
43     }
44 }
View Code

 

Attention:

Sometimes it may have Time Limit Exceeded error....

posted on 2013-05-19 09:32  freeneng  阅读(143)  评论(0编辑  收藏  举报

导航