leetcode题解-有效的数独

文章目录

代码

/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function(board) {
    
    
    let row=[{
    
    },{
    
    },{
    
    },{
    
    },{
    
    },{
    
    },{
    
    },{
    
    },{
    
    }];
    let column=[{
    
    },{
    
    },{
    
    },{
    
    },{
    
    },{
    
    },{
    
    },{
    
    },{
    
    }];
    let box = [{
    
    },{
    
    },{
    
    },{
    
    },{
    
    },{
    
    },{
    
    },{
    
    },{
    
    }];
    for(let i=0;i<9;i++){
    
    
        for(let j=0;j<9;j++){
    
    
            let item = board[i][j];
            let boxIndex = parseInt(i/3) * 3 + parseInt(j/3);
            if(item!='.'){
    
    
                if(row[i][item]||column[j][item]||box[boxIndex][item]){
    
    
                    return false
                }else{
    
    
                    row[i][item]=1;
                    column[j][item]=1;
                    box[boxIndex][item]=1;
                }
            }
        }
    }
    return true
}

思路

有效数独的意思三条规则

  1. 同一行没有重复的数字
  2. 同一列没有重复的数字
  3. 同一个小九宫格没有重复的数字

利用hashmap 来检测重复数据
每一个数字都有三种身份 它既属于一行 又属于某一列 还属于某一个九宫格。
只要知道它所属的位置 在对应的规则检测map表中查找
如果不存在 就映射进去
如果已经存在就返回 false

猜你喜欢

转载自blog.csdn.net/weixin_38616850/article/details/106392487