leetcode-有效的數獨
阿新 • • 發佈:2018-12-09
判斷一個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。
數字 1-9 在每一行只能出現一次。
數字 1-9 在每一列只能出現一次。
數字 1-9 在每一個以粗實線分隔的 3x3 宮內只能出現一次。
上圖是一個部分填充的有效的數獨。
數獨部分空格內已填入了數字,空白格用 ‘.’ 表示。
示例 1:
輸入: [ ["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
示例 2:
輸入: [ ["8","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"] ] 輸出: false
解釋: 除了第一行的第一個數字從 5 改為 8 以外,空格內其他數字均與 示例1 相同。
但由於位於左上角的 3x3 宮內有兩個 8 存在, 因此這個數獨是無效的。
說明:
一個有效的數獨(部分已被填充)不一定是可解的。
只需要根據以上規則,驗證已經填入的數字是否有效即可。
給定數獨序列只包含數字 1-9 和字元 ‘.’ 。
給定數獨永遠是 9x9 形式的。
程式碼
/**
* @param {character[][]} board
* @return {boolean}
*/
var isValidSudoku = function(board) {
let rows = {};
let ranks = {};
let react = {};
let result = true;
for(let n=0;n<board.length;n++){
for(let m=0;m<board[n].length;m++){
let value = board[n][m]
if(value != '.'){
if(!rows[n]){
rows[n] ={}
}
if(!ranks[m]){
ranks[m]={}
}
//條件一
if(!rows[n][value]){
rows[n][value] = true
}else{
result = false;
}
//條件二
if(!ranks[m][value]){
ranks[m][value] = true;
}else{
result = false;
}
//條件三
let rowsN = Math.ceil((n+1)/3);
let ranksM = Math.ceil((m+1)/3);
if(!react[rowsN]){
react[rowsN] = {}
}
if( !react[rowsN][ranksM] ){
react[rowsN][ranksM] = {}
}
if(!react[rowsN][ranksM][value]){
react[rowsN][ranksM][value] = true
}else{
result = false;
}
}
}
}
return result
};