標籤:
https://leetcode.com/problems/valid-sudoku/
Valid Sudoku
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character ‘.‘
.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
正好用了一下最近get的新姿勢,沒有用map存1-9是否訪問過。
一個變數_bit就記下了這新資訊,用位元運算。
比如來的數是4,就是100,與_bit做位與,如果沒有出現過100&000是0,否則100&100不等於0,最後用100|000記下4已經訪問過了。
人蔘第一次使用四重迴圈。這種酸爽不敢相信,我用腳趾猜row,column,square這3種情況可以合并,但是為了紀念我人生的第一次四重迴圈,就這樣吧(其實是懶。
1 /** 2 * @param {character[][]} board 3 * @return {boolean} 4 */ 5 var isValidSudoku = function(board) { 6 this._bit = 0; 7 function isValid(num){ 8 var tmp = Math.pow(2, num - 1); 9 if((this._bit & tmp) !== 0){10 return false;11 }else{12 this._bit = this._bit | tmp;13 return true;14 }15 }16 17 var i = 0, j = 0, m = 0, n =0, cell = 0;18 //row19 for(i = 0; i < 9; i++){20 for(j = 0; j < 9; j++){21 cell = parseInt(board[i][j]);22 if(!isValid(cell)){23 return false;24 }25 }26 this._bit = 0;27 }28 //column29 for(i = 0; i < 9; i++){30 for(j = 0; j < 9; j++){31 cell = parseInt(board[j][i]);32 if(!isValid(cell)){33 return false;34 }35 }36 this._bit = 0;37 }38 //square39 for(i = 0; i <= 6; i+=3){40 for(j = 0; j <=6 ; j+=3){41 for(m = 0; m < 3; m++){42 for(n = 0; n < 3; n++){43 cell = parseInt(board[m + i][n + j]);44 if(!isValid(cell)){45 return false;46 }47 }48 }49 this._bit = 0;50 }51 }52 return true;53 };
[LeetCode][JavaScript]Valid Sudoku