[36] 有效的数独 js

题目描述:

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

*

*

* 数字 1-9 在每一行只能出现一次。

* 数字 1-9 在每一列只能出现一次。

* 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)

注意:

* 一个有效的数独(部分已被填充)不一定是可解的。

* 只需要根据以上规则,验证已经填入的数字是否有效即可。

* 空白格用 '.' 表示。

输入:board =

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

解题思路:

  1. 先校验横向和竖向是否有重复,对于任意一个位置的数字来说,只有这一行没有重复的,并且这一列也没有重复的,说明这个数横竖符合条件.

  2. 然后判断3*3的九宫格是否有重复

解法一:

function isValidSudoku(board) {
     // 用来存放行的map
    let rowMap = new Map();
    // 用来存放列的map
    let columnMap = new Map();
    // 存放返回的结果
    let res = true;
    // 先校验横向和竖向是否有重复,对于任意一个位置的数字来说,只有这一行没有重复的,
    //并且这一列也没有重复的,说明这个数横竖符合条件
    // 所以要做的就是判断每一行每一列是否有重复的数字,这里行列一起判断,别浪费循环
    for (let i = 0; i < 9; i++) {
        for (let j = 0; j < 9; j++) {
            if (rowMap.has(board[i][j])) {
                res = false;
                break;
            } else {
                if (board[i][j] !== '.') {
                    rowMap.set(board[i][j], 1);
                }
            }
            if (columnMap.has(board[j][i])) {
                res = false;
                break;
            } else {
                if (board[j][i] !== '.') {
                    columnMap.set(board[j][i], 1);
                }
            }
        }
        // 每一行列判断完以后要清空两个map
        rowMap.clear();
        columnMap.clear();
    }

    // 如果行列判断完已经有重复了,就不用判断后面的九格内不重复了
    if (!res) {
        return res;
    }

    // 三行为一轮循环,这两个变量记录第几次行/列的跳跃,先把行的三次判断完,
    // 然后换下一组9个的
    let rown = 0;
    let coln = 0;

    // 然后检查九宫格是否有重复
    while (rown < 3 && coln < 3) {
        for (let i = 0; i < 3; i++) {
            for (let j = 0; j < 3; j++) {
                if (rowMap.has(board[rown * 3 + i][coln * 3 + j])) {
                    res = false;
                    break;
                } else {
                    if (board[rown * 3 + i][coln * 3 + j] !== '.') {
                        rowMap.set(board[rown * 3 + i][coln * 3 + j], 1);
                    }  
                }
            }
        }
        rown = rown + 1;
        rowMap.clear();
        if (rown === 3) {
            coln = coln + 1;
            rown = 0;
        }
    }
    return res;
};

用时:

//507/507 cases passed (76 ms)

// Your runtime beats 84.31 % of typescript submissions

// Your memory usage beats 91.5 % of typescript submissions (44.3 MB)

你可能感兴趣的:(leetcode,算法,leetcode,javascript)