有效的数独

题目描述:请你判断一个 9x9 的数独是否有效。只需要 根据以下规则 ,验证已经填入的数字是否有效即可。

数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)
数独部分空格内已填入了数字,空白格用 ‘.’ 表示。

注意:

  • 一个有效的数独(部分已被填充)不一定是可解的。
  • 只需要根据以上规则,验证已经填入的数字是否有效即可。

示例说明请见LeetCode官网。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-sudoku/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解法一:数组遍历

分为3种情况判断,分别是行判断、列判断、3*3宫内判断,判断逻辑是利用Set判重,如果在同一行(或同一列、同一宫内)有重复的数字,则返回false;如果都符合,最后返回true。

  1. import javafx.util.Pair;
  2. import java.util.ArrayList;
  3. import java.util.HashSet;
  4. import java.util.List;
  5. import java.util.Set;
  6. public class LeetCode_036 {
  7. public static List<Pair<Integer, Integer>> all = new ArrayList<>();
  8. static {
  9. all.add(new Pair<>(0, 0));
  10. all.add(new Pair<>(0, 3));
  11. all.add(new Pair<>(0, 6));
  12. all.add(new Pair<>(3, 0));
  13. all.add(new Pair<>(3, 3));
  14. all.add(new Pair<>(3, 6));
  15. all.add(new Pair<>(6, 0));
  16. all.add(new Pair<>(6, 3));
  17. all.add(new Pair<>(6, 6));
  18. }
  19. public static boolean isValidSudoku(char[][] board) {
  20. // 行判断
  21. for (int i = 0; i < board.length; i++) {
  22. Set<Character> nums = new HashSet<>();
  23. for (int j = 0; j < board[i].length; j++) {
  24. if (board[i][j] != '.' && !nums.add(board[i][j])) {
  25. return false;
  26. }
  27. }
  28. }
  29. // 列判断
  30. for (int i = 0; i < board.length; i++) {
  31. Set<Character> nums = new HashSet<>();
  32. for (int j = 0; j < board.length; j++) {
  33. if (board[j][i] != '.' && !nums.add(board[j][i])) {
  34. return false;
  35. }
  36. }
  37. }
  38. // 宫内判断
  39. for (Pair<Integer, Integer> integerIntegerPair : all) {
  40. Set<Character> nums = new HashSet<>();
  41. for (int x = integerIntegerPair.getKey(); x < integerIntegerPair.getKey() + 3; x++) {
  42. for (int y = integerIntegerPair.getValue(); y < integerIntegerPair.getValue() + 3; y++) {
  43. if (board[x][y] != '.' && !nums.add(board[x][y])) {
  44. return false;
  45. }
  46. }
  47. }
  48. }
  49. return true;
  50. }
  51. public static void main(String[] args) {
  52. char[][] board = new char[][]{{'5', '3', '.', '.', '7', '.', '.', '.', '.'}
  53. , {'6', '.', '.', '1', '9', '5', '.', '.', '.'}
  54. , {'.', '9', '8', '.', '.', '.', '.', '6', '.'}
  55. , {'8', '.', '.', '.', '6', '.', '.', '.', '3'}
  56. , {'4', '.', '.', '8', '.', '3', '.', '.', '1'}
  57. , {'7', '.', '.', '.', '2', '.', '.', '.', '6'}
  58. , {'.', '6', '.', '.', '.', '.', '2', '8', '.'}
  59. , {'.', '.', '.', '4', '1', '9', '.', '.', '5'}
  60. , {'.', '.', '.', '.', '8', '.', '.', '7', '9'}};
  61. System.out.println(isValidSudoku(board));
  62. }
  63. }

【每日寄语】 希望生活给予你风浪的同时,也给你阳光作为回报,让你感受到这个世界的温柔。