代码改变世界

leetcode - Valid Sudoku

2013-11-10 10:16  张汉生  阅读(186)  评论(0编辑  收藏  举报

 

 1 class Solution {
 2 public:
 3     bool isValidSudoku(vector<vector<char> > &board) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         bool a[9][9];
 7         bool b[9][9];
 8         bool ct[9][9];
 9         if (board.size() != 9 || board[0].size() != 9)
10             return false;
11         for (int i = 0; i < 9; i++){
12             for (int j = 0; j < 9; j++){
13                 a[i][j] = false;
14                 b[i][j] = false;
15                 ct[i][j] = false;
16             }
17         }
18         for (int i = 0; i < 9; i++){
19             for (int j = 0; j < 9; j++){
20                 char c = board[i][j];
21                 if (c == '.')
22                     continue;
23                 else if (c < '1' || c>'9')
24                     return false;
25                 int index = c - '1';
26                 if (a[i][index])
27                     return false;
28                 a[i][index] = true;
29                 if (b[j][index])
30                     return false;
31                 b[j][index] = true;
32                 int cIndex = 3*(i/3) + j/3;
33                 if (ct[cIndex][index])
34                     return false;
35                 ct[cIndex][index] = true;
36             }
37         }
38         return true;
39     }
40 };