LeetCode——有效的数独

题目:

判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
上图是一个部分填充的有效的数独。
数独部分空格内已填入了数字,空白格用 '.' 表示。
输入:
[
    ["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

思路:

为提高计算速度,尽量只进行一次迭代
遍历数组,判断在同一行、同一列、同一3*3宫格内是否有重复数字
判断重复数字方法:
    以每行、列、3*3宫格为单位生成对象,使用宫格中的数字作为关键字,记录该数字是否出现过(若未出现则记录标记,已出现则数独无效返回false)
    并将对象分别放入对应的行、列、3*3宫格数组中
    遍历结束则返回true

/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function(board) {
    var i, j, columns = [],rows = [],grids = [];
    for(i=0;i<board.length;i++){
        columns.push({});
        rows.push({});
        grids.push({});
    }
    for(i=0;i<board.length;i++){
        for(j=0;j<board[i].length;j++){
            if(board[i][j] == ".")continue;
            if(rows[i][board[i][j]] != null || columns[j][board[i][j]] != null || grids[Math.floor(i/3)*3+Math.floor(j/3)][board[i][j]]){
                return false;
            }else{
                rows[i][board[i][j]] = '1';
                columns[j][board[i][j]] = '1';
                grids[Math.floor(i/3)*3+Math.floor(j/3)][board[i][j]] = '1';
            }
        }
    }
    return true;
};

代码地址:github地址

发布了31 篇原创文章 · 获赞 53 · 访问量 8万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览