題目描述:
請你判斷一個?9 x 9 的數獨是否有效。只需要 根據以下規則 ,驗證已經填入的數字是否有效即可。
*
*
* 數字?1-9?在每一行只能出現一次。
* 數字?1-9?在每一列只能出現一次。
* 數字?1-9?在每一個以粗實線分隔的?3x3?宮內只能出現一次。(請參考示例圖)
注意:
* 一個有效的數獨(部分已被填充)不一定是可解的。
* 只需要根據以上規則,驗證已經填入的數字是否有效即可。
* 空白格用?'.'?表示。
輸入:board =
* [["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的九宮格是否有重復
解法一:
function isValidSudoku(board) {// 用來存放行的maplet rowMap = new Map();// 用來存放列的maplet columnMap = new Map();// 存放返回的結果let res = true;// 先校驗橫向和豎向是否有重復,對于任意一個位置的數字來說,只有這一行沒有重復的,//并且這一列也沒有重復的,說明這個數橫豎符合條件// 所以要做的就是判斷每一行每一列是否有重復的數字,這里行列一起判斷,別浪費循環for (let i = 0; i < 9; i++) {for (let j = 0; j < 9; j++) {if (rowMap.has(board[i][j])) {res = false;break;} else {if (board[i][j] !== '.') {rowMap.set(board[i][j], 1);}}if (columnMap.has(board[j][i])) {res = false;break;} else {if (board[j][i] !== '.') {columnMap.set(board[j][i], 1);}}}// 每一行列判斷完以后要清空兩個maprowMap.clear();columnMap.clear();}// 如果行列判斷完已經有重復了,就不用判斷后面的九格內不重復了if (!res) {return res;}// 三行為一輪循環,這兩個變量記錄第幾次行/列的跳躍,先把行的三次判斷完,// 然后換下一組9個的let rown = 0;let coln = 0;// 然后檢查九宮格是否有重復while (rown < 3 && coln < 3) {for (let i = 0; i < 3; i++) {for (let j = 0; j < 3; j++) {if (rowMap.has(board[rown * 3 + i][coln * 3 + j])) {res = false;break;} else {if (board[rown * 3 + i][coln * 3 + j] !== '.') {rowMap.set(board[rown * 3 + i][coln * 3 + j], 1);} }}}rown = rown + 1;rowMap.clear();if (rown === 3) {coln = coln + 1;rown = 0;}}return res;
};
用時:
//507/507 cases passed (76 ms)
// Your runtime beats 84.31 % of typescript submissions
// Your memory usage beats 91.5 % of typescript submissions (44.3 MB)