Skip to content

Latest commit

 

History

History
99 lines (84 loc) · 3.58 KB

36. 有效的数独.md

File metadata and controls

99 lines (84 loc) · 3.58 KB

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

  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 形式的。

解题思路

  1. 首先,需要判断的是三种,行,列,块
  2. 所以,分别定义3个变量记录,行Set,列Set,和块的SetList(因为块不方便遍历,所以不能重复使用,只能用放在数组里)
  3. 对于行判断,i为行,j为列,如果是从头开始,j=0,那么清空,如果已经存了这个数,就代表重复,返回false,否则放入rowSet
  4. 对于列判断,道理类似,只是把i看作列,j看作行,所以只用一遍双循环
  5. 对于块,首先一共9块,看作3行3列,可以通过除以3操作得到在哪一行哪一列,因为是一维数组,所以通过行数 * 3 + 列数得到索引,判断道理类似 (不知道这方法好不好)

solution:

  • 利用set数据类型来存储已有的遍历
  • 时间复杂度O(n^2^),空间复杂度O(1)
/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function(board) {
    const rowSet = new Set()
    const columnSet = new Set()
    const setList = Array.from({ length: 9 }, () => new Set())
    for(let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            const m = parseInt(i / 3)
            const n = parseInt(j / 3)
            const idx = m * 3 + n // setList的索引
            if (j === 0) {
                rowSet.clear()
                columnSet.clear()
            }
            if (rowSet.has(board[i][j]) || columnSet.has(board[j][i])) return false
            if (setList[idx].has(board[i][j])) return false
            board[i][j] !== '.' && setList[idx].add(board[i][j])
            board[i][j] !== '.' && rowSet.add(board[i][j])
            board[j][i] !== '.' && columnSet.add(board[j][i])
        }
    }
    return true
};