1. 程式人生 > >[leetcode]36題 Valid Sudoku的JavaScript解法

[leetcode]36題 Valid Sudoku的JavaScript解法

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.

主要歷程
1 理解題目,這道題不是填數獨,而是valid數獨而且如果有看Note,會發現

Only the filled cells need to be validated.

這局決定了 ‘.’是不校驗的,是返回true的。

2 九宮數獨的規則一共有3個,行檢驗,和列檢驗比較簡單。主要是用js去做 除法得到的浮點數用於陣列比較坑爹。必須向下取整Math.floor()才能用於索引。。

3還有array 並沒有clear方法也要注意!

4 九宮的數是 1-9的,所以轉成索引是減去 ‘1’的!

/**
 * @param {character[][]} board
 * @return
{boolean} */
var checkedArray = new Array(9) var isValidSudoku = function(board) { for (var i = 0 ; i < board.length ; i++) { checkedArray.fill(0) for(var j = 0 ; j < board.length ; j ++) { if (checkValue(board[i][j]) === false ) { return
false } } } for ( i = 0 ; i < board.length ; i++) { checkedArray.fill(0) for( j = 0 ; j < board.length ; j++) { if (checkValue(board[j][i]) === false ) { return false } } } checkedArray.fill(0) for ( i = 0 ; i < board.length ; i+=3) { for( j = 0 ; j < board.length ; j+=3) { checkedArray.fill(0) for (var k = 0 ; k < 9; k++) { // console.log("checking "+i+ k/3+" , "+j + k%3) if (checkValue(board[i+ Math.floor(k/3)][j + k%3]) === false ) { return false } } } } return true; }; var checkValue = function(value) { // console.log("checking value "+value) if(value == '.') //根據題意不校驗 { return true; } var index = value - '1'; if (index < 0 || index > 9 || checkedArray[index] > 0) { // console.log("value is "+index +"/" +checkedArray[index]) return false; } else { // console.log("push index is "+index) checkedArray[index] = 1; } return true; }