Valid Sudoku

描述

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules http://sudoku.com.au/TheRules.aspx .

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

Valid Sudoku

Figure: Valid Sudoku

分析

细节实现题。

代码

  1. // Valid Sudoku
  2. // 时间复杂度O(n^2),空间复杂度O(1)
  3. class Solution {
  4. public:
  5. bool isValidSudoku(const vector<vector<char>>& board) {
  6. bool used[9];
  7. for (int i = 0; i < 9; ++i) {
  8. fill(used, used + 9, false);
  9. for (int j = 0; j < 9; ++j) // 检查行
  10. if (!check(board[i][j], used))
  11. return false;
  12. fill(used, used + 9, false);
  13. for (int j = 0; j < 9; ++j) // 检查列
  14. if (!check(board[j][i], used))
  15. return false;
  16. }
  17. for (int r = 0; r < 3; ++r) // 检查 9 个子格子
  18. for (int c = 0; c < 3; ++c) {
  19. fill(used, used + 9, false);
  20. for (int i = r * 3; i < r * 3 + 3; ++i)
  21. for (int j = c * 3; j < c * 3 + 3; ++j)
  22. if (!check(board[i][j], used))
  23. return false;
  24. }
  25. return true;
  26. }
  27. bool check(char ch, bool used[9]) {
  28. if (ch == '.') return true;
  29. if (used[ch - '1']) return false;
  30. return used[ch - '1'] = true;
  31. }
  32. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/cpp/linear-list/array/valid-sudoku.html