[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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值