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

 

分析:行、列、3x3 box 分布check

 1 class Solution {
 2     public:
 3         bool m_used[9];
 4         bool isValidSudoku(const vector<vector<char>>& board) {
 5 
 6             // check the row
 7             for (int i = 0; i < 9; ++i) {
 8                 fill(m_used, m_used + 9, false);
 9                 for (int j = 0; j < 9; ++j)
10                 {
11                     if (!check(board[i][j]))
12                         return false;
13                     m_used[board[i][j] - '1'] = true;
14                 }
15             }
16 
17             // check the column
18             for (int i = 0; i < 9; ++i) {
19                 fill(m_used, m_used + 9, false);
20                 for (int j = 0; j < 9; ++j)
21                 {   
22                     if (!check(board[j][i]))
23                         return false;
24                     m_used[board[j][i] - '1'] = true;
25                 }   
26             }   
27 
28             // check the 3x3 box
29             for (int r = 0; r < 3; ++r)
30                 for( int c = 0; c < 3; ++c)
31                 {
32                     fill(m_used, m_used + 9, false);
33                     for (int i = r * 3; i < r * 3 + 3; ++i)
34                         for (int j = c * 3; j < c * 3 + 3; ++j)
35                         {
36                             if (!check(board[i][j]))
37                                 return false;
38                             m_used[board[i][j] - '1'] = true;
39                         }
40                 }
41         return true;
42         }
43         bool check(char ch) {
44             if (ch == '.') return true;
45             if (m_used[ch - '1'] == true)
46                 return false;
47             else
48                 return true;
49         }
50 };

 

posted @ 2014-06-25 16:45  穆穆兔兔  阅读(168)  评论(0编辑  收藏  举报