|
| 1 | +## Valid Sudoku |
| 2 | + |
| 3 | +Determine if a Sudoku is valid, according to: [Sudoku Puzzles - The Rules](http://sudoku.com.au/TheRules.aspx). |
| 4 | + |
| 5 | +The Sudoku board could be partially filled, where empty cells are filled with the character '.'. |
| 6 | + |
| 7 | + |
| 8 | +A partially filled sudoku which is valid. |
| 9 | + |
| 10 | +Note: |
| 11 | +*A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated. |
| 12 | + |
| 13 | +Subscribe to see which companies asked this question* |
| 14 | + |
| 15 | +## Solution |
| 16 | + |
| 17 | +此题是纯粹的模拟题,只需要根据数独的规则分别判断每一行、每一列、每一个九宫格是否出现重复数字即可。判断数字是否重复使用hash表即可。 |
| 18 | + |
| 19 | +### 判断每一行 |
| 20 | + |
| 21 | +```cpp |
| 22 | +bool check_row(const vector<vector<char>> &a, int row) { |
| 23 | + vector<bool> used(9, false); |
| 24 | + for (char i : a[row]) { |
| 25 | + if ('.' == i) |
| 26 | + continue; |
| 27 | + int pos = i - '0' - 1; |
| 28 | + if (used[pos]) |
| 29 | + return false; |
| 30 | + else |
| 31 | + used[pos] = true; |
| 32 | + } |
| 33 | + return true; |
| 34 | +} |
| 35 | +``` |
| 36 | +
|
| 37 | +### 判断每一列 |
| 38 | +
|
| 39 | +```cpp |
| 40 | +bool check_col(const vector<vector<char>> &a, int col) { |
| 41 | + vector<bool> used(9, false); |
| 42 | + for (int i = 0; i < 9; ++i) { |
| 43 | + if (a[i][col] == '.') |
| 44 | + continue; |
| 45 | + int pos = a[i][col] - '0' - 1; |
| 46 | + if (used[pos]) |
| 47 | + return false; |
| 48 | + else |
| 49 | + used[pos] = true; |
| 50 | + } |
| 51 | + return true; |
| 52 | +} |
| 53 | +``` |
| 54 | + |
| 55 | +### 判断每一个九宫格 |
| 56 | + |
| 57 | +需要注意确定每一个九宫格对应行首和列首,假设九宫格从0开始编号,则第n个九宫格的行位置为`n / 3 * 3`, 列位置为`n % 3 * 3` |
| 58 | + |
| 59 | +```cpp |
| 60 | +bool check_box(const vector<vector<char>> &a, int box) { |
| 61 | + int row_begin = box / 3 * 3; |
| 62 | + int col_begin = box % 3 * 3; |
| 63 | + vector<bool> used(9, false); |
| 64 | + for (int i = row_begin; i < row_begin + 3; ++i) { |
| 65 | + for (int j = col_begin; j < col_begin + 3; ++j) { |
| 66 | + if (a[i][j] == '.') |
| 67 | + continue; |
| 68 | + int pos = a[i][j] - '0' - 1; |
| 69 | + if (used[pos]) |
| 70 | + return false; |
| 71 | + else |
| 72 | + used[pos] = true; |
| 73 | + } |
| 74 | + } |
| 75 | + return true; |
| 76 | +} |
| 77 | +``` |
| 78 | +
|
| 79 | +实习代码为: |
| 80 | +
|
| 81 | +```cpp |
| 82 | +bool isValidSudoku(vector<vector<char>>& board) { |
| 83 | + for (int i = 0; i < 9; ++i) { |
| 84 | + if (!(check_row(board, i) |
| 85 | + && (check_col(board, i)) |
| 86 | + && (check_box(board, i))) |
| 87 | + ) |
| 88 | + return false; |
| 89 | + } |
| 90 | + return true; |
| 91 | +} |
| 92 | +``` |
0 commit comments