1. 程式人生 > 其它 >Day23 有效的數獨

Day23 有效的數獨

技術標籤:LeetCode刷題集演算法leetcode資料結構

判斷一個 9x9 的數獨是否有效。只需要根據規則,驗證已經填入的數字是否有效即可

https://leetcode-cn.com/problems/valid-sudoku/

  1. 數字 1-9 在每一行只能出現一次。
  2. 數字 1-9 在每一列只能出現一次。
  3. 數字 1-9 在每一個以粗實線分隔的 3x3 宮內只能出現一次。

示例1:

輸入:
[
[“5”,“3”,".",".",“7”,".",".",".","."],
[“6”,".",".",“1”,“9”,“5”,".",".","."],

[".",“9”,“8”,".",".",".",".",“6”,"."],
[“8”,".",".",".",“6”,".",".",".",“3”],
[“4”,".",".",“8”,".",“3”,".",".",“1”],
[“7”,".",".",".",“2”,".",".",".",“6”],
[".",“6”,".",".",".",".",“2”,“8”,"."],
[".",".",".",“4”,“1”,“9”,".",".",“5”],
[".",".",".",".",“8”,".",".",“7”,“9”]
]
輸出: true

示例2:

輸入:
[
[“8”,“3”,".",".",“7”,".",".",".","."],
[“6”,".",".",“1”,“9”,“5”,".",".","."],
[".",“9”,“8”,".",".",".",".",“6”,"."],
[“8”,".",".",".",“6”,".",".",".",“3”],
[“4”,".",".",“8”,".",“3”,".",".",“1”],
[“7”,".",".",".",“2”,".",".",".",“6”],
[".",“6”,".",".",".",".",“2”,“8”,"."],
[".",".",".",“4”,“1”,“9”,".",".",“5”],
[".",".",".",".",“8”,".",".",“7”,“9”]
]
輸出: false
解釋: 除了第一行的第一個數字從 5 改為 8 以外,空格內其他數字均與 示例1 相同。
但由於位於左上角的 3x3 宮內有兩個 8 存在, 因此這個數獨是無效的。

提示:

一個有效的數獨(部分已被填充)不一定是可解的。
只需要根據以上規則,驗證已經填入的數字是否有效即可。
給定數獨序列只包含數字 1-9 和字元 ‘.’ 。
給定數獨永遠是 9x9 形式的。

Java解法

思路:

  • 就是按照規則來匹中是否有重複
  • 第一步:規則資料集合
  • 第二步:查重驗證 演算法正確,效率不高

官方解

https://leetcode-cn.com/problems/valid-sudoku/solution/you-xiao-de-shu-du-by-leetcode/

  1. 一次迭代

    遍歷陣列
    確認數值是否違反規則

    class Solution {
      public boolean isValidSudoku(char[][] board) {
        // init data
        HashMap<Integer, Integer> [] rows = new HashMap[9];
        HashMap<Integer, Integer> [] columns = new HashMap[9];
        HashMap<Integer, Integer> [] boxes = new HashMap[9];
        for (int i = 0; i < 9; i++) {
          rows[i] = new HashMap<Integer, Integer>();
          columns[i] = new HashMap<Integer, Integer>();
          boxes[i] = new HashMap<Integer, Integer>();
        }
    
        // validate a board
        for (int i = 0; i < 9; i++) {
          for (int j = 0; j < 9; j++) {
            char num = board[i][j];
            if (num != '.') {
              int n = (int)num;
              int box_index = (i / 3 ) * 3 + j / 3;
    
              // keep the current cell value
              rows[i].put(n, rows[i].getOrDefault(n, 0) + 1);
              columns[j].put(n, columns[j].getOrDefault(n, 0) + 1);
              boxes[box_index].put(n, boxes[box_index].getOrDefault(n, 0) + 1);
    
              // check if this value has been already seen before
              if (rows[i].get(n) > 1 || columns[j].get(n) > 1 || boxes[box_index].get(n) > 1)
                return false;
            }
          }
        }
    
        return true;
      }
    }
    
    • 時間複雜度:O(1)

    • 空間複雜度:O(1)