[leetcode]36题 Valid Sudoku的JavaScript解法

来源:互联网 发布:淘宝二手卖家问题退货 编辑:程序博客网 时间:2024/05/02 21:17

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;}
0 0
原创粉丝点击