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. public class Solution {
  4. public boolean isValidSudoku(char[][] board) {
  5. boolean[] used = new boolean[9];
  6. for (int i = 0; i < 9; ++i) {
  7. Arrays.fill(used, false);
  8. for (int j = 0; j < 9; ++j) // 检查行
  9. if (!check(board[i][j], used))
  10. return false;
  11. Arrays.fill(used, false);
  12. for (int j = 0; j < 9; ++j) // 检查列
  13. if (!check(board[j][i], used))
  14. return false;
  15. }
  16. for (int r = 0; r < 3; ++r) // 检查 9 个子格子
  17. for (int c = 0; c < 3; ++c) {
  18. Arrays.fill(used, false);
  19. for (int i = r * 3; i < r * 3 + 3; ++i)
  20. for (int j = c * 3; j < c * 3 + 3; ++j)
  21. if (!check(board[i][j], used))
  22. return false;
  23. }
  24. return true;
  25. }
  26. private static boolean check(char ch, boolean[] used) {
  27. if (ch == '.') return true;
  28. if (used[ch - '1']) return false;
  29. return used[ch - '1'] = true;
  30. }
  31. };

相关题目

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