minjs1cn / weekly-learning

每周学习分享打卡
0 stars 0 forks source link

36 -【leetcode】有效的数独 #36

Open xieshiyi opened 3 years ago

xieshiyi commented 3 years ago

有效的数独

xieshiyi commented 3 years ago
/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function(board) {
    // 横向,纵向,3宫格分别存储对应hash值
    let rows = {};
    let columns = {};
    let boxes = {};
    // 遍历数独
    for(let i = 0; i < 9; i++) {
        for(let j = 0; j < 9; j++) {
            let num = board[i][j]
            if(num !== '.'){
                // 创建宫格内的对应key
                const boxIndex = parseInt((i/3)) * 3 + parseInt(j/3)
                // 任意hash-map中发现已存在对应的内容,则为false
                if(rows[`${i}-${num}`] || columns[`${j}-${num}`] || boxes[`${boxIndex}-${num}`]) {
                    return false
                }
                rows[`${i}-${num}`] = true
                columns[`${j}-${num}`] = true
                boxes[`${boxIndex}-${num}`] = true
            }
        }
    }
    return true;
};
wucuiping commented 3 years ago

/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function(board) {
    let rows = []; // 对象数组,key是值,val是个数
    let cols = [];
    let boxes = [];
    for (let i=0; i<9; i++) {
        const boxR = Math.floor(i / 3 )
        if (!rows[i]) {
            rows[i] = {}
        }
        for(let j=0; j<9; j++){
            if (!cols[j]) {
                cols[j] = {}
            }
            const val = board[i][j]
            if (val !== '.'){
                // 处理行
                if (val in rows[i]) {
                    // 这行已经存在val了,说明重复了
                    return false
                } else {
                    rows[i][val] = 1
                }
                // 处理列
                if (val in cols[j]) {
                    // 这列已经存在val了,说明重复了
                    return false
                } else {
                    cols[j][val] = 1
                }

                // 处理3*3
                const boxC = Math.floor(j / 3)
                const b = boxR*3+boxC
                if (!boxes[b]) {
                    boxes[b] ={}
                }
                if (val in boxes[b]) {
                    return false
                } else {
                    boxes[b][val] = 1
                }
            }
        }
    }
    return true
};
```javascript