Valid Sudoku

Question

  1. Determine whether a Sudoku is valid.
  2. The Sudoku board could be partially filled,
  3. where empty cells are filled with the character ..
  4. Example
  5. The following partially filed sudoku is valid.

valid-sudoku.png

  1. Valid Sudoku
  2. Note
  3. A valid Sudoku board (partially filled) is not necessarily solvable.
  4. Only the filled cells need to be validated.
  5. Clarification
  6. What is Sudoku?
  7. http://sudoku.com.au/TheRules.aspx
  8. https://zh.wikipedia.org/wiki/%E6%95%B8%E7%8D%A8
  9. https://en.wikipedia.org/wiki/Sudoku
  10. http://baike.baidu.com/subview/961/10842669.htm

题解

看懂数独的含义就好了,分为三点考虑,一是每行无重复数字;二是每列无重复数字;三是小的九宫格中无重复数字。

Java

  1. class Solution {
  2. /**
  3. * @param board: the board
  4. @return: wether the Sudoku is valid
  5. */
  6. public boolean isValidSudoku(char[][] board) {
  7. if (board == null || board.length == 0) return false;
  8. // check row
  9. for (int i = 0; i < 9; i++) {
  10. boolean[] numUsed = new boolean[9];
  11. for (int j = 0; j < 9; j++) {
  12. if (isDuplicate(board[i][j], numUsed)) {
  13. return false;
  14. }
  15. }
  16. }
  17. // check column
  18. for (int i = 0; i < 9; i++) {
  19. boolean[] numUsed = new boolean[9];
  20. for (int j = 0; j < 9; j++) {
  21. if (isDuplicate(board[j][i], numUsed)) {
  22. return false;
  23. }
  24. }
  25. }
  26. // check sub box
  27. for (int i = 0; i < 9; i = i + 3) {
  28. for (int j = 0; j < 9; j = j + 3) {
  29. if (!isValidBox(board, i, j)) {
  30. return false;
  31. }
  32. }
  33. }
  34. return true;
  35. }
  36. private boolean isValidBox(char[][] box, int x, int y) {
  37. boolean[] numUsed = new boolean[9];
  38. for (int i = x; i < x + 3; i++) {
  39. for (int j = y; j < y + 3; j++) {
  40. if (isDuplicate(box[i][j], numUsed)) {
  41. return false;
  42. }
  43. }
  44. }
  45. return true;
  46. }
  47. private boolean isDuplicate(char c, boolean[] numUsed) {
  48. if (c == '.') {
  49. return false;
  50. } else if (numUsed[c - '1']) {
  51. return true;
  52. } else {
  53. numUsed[c - '1'] = true;
  54. return false;
  55. }
  56. }
  57. }

源码分析

首先实现两个小的子功能模块判断是否有重复和小的九宫格是否重复。

复杂度分析

Reference

  • Soulmachine 的 leetcode 题解