# LeetCode——有效的数独

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

以每行、列、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;
};

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