LeetCode36.有效的數獨 JavaScript

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

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

上圖是一個部分填充的有效的數獨。java

數獨部分空格內已填入了數字,空白格用 '.' 表示。spa

示例 1:
輸入:code

[
  ["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"]
]

輸出: trueblog

示例 2:
輸入:ip

[
  ["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 相同。it

但因爲位於左上角的` 3x3` 宮內有兩個 `8` 存在, 所以這個數獨是無效的。

說明:
一個有效的數獨(部分已被填充)不必定是可解的。
只須要根據以上規則,驗證已經填入的數字是否有效便可。
給定數獨序列只包含數字 1-9 和字符 '.'
給定數獨永遠是 9x9 形式的。io

答案參考:function

/**
 * @param {character[][]} board
 * @return {boolean}
 */

var isValidSudoku = function(board) {
//   檢查每一行
  for (let arr of board) {            
    let row = []
    for (let c of arr) {
      if (c !== '.') row.push(c);
    }
    let set = new Set(row)
    if (set.size !== row.length) return false;
  }
  
//   檢查每一列
  for (let i = 0; i < 9; i++) {
    let col = []
    board.map( arr => {
      if (arr[i] !== '.') col.push(arr[i])
    })
    let set = new Set(col)
    if (set.size !== col.length) return false;
  }
  
//   檢查每一個小方塊
  for (let x = 0; x < 9; x += 3) {
    for (let y = 0; y < 9; y += 3) {
      let box = []
      for (let a = x; a < 3 + x; a ++) {
        for (let b = y; b < 3 + y; b ++) {
          if (board[a][b] !== '.') box.push(board[a][b])
        }
      }
      let set = new Set(box)
      if (set.size !== box.length) return false
    }
  }
  
  return true
};

相關文章
相關標籤/搜索