36. 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.

就走一遍二维数组,行列同时走,用两个对象记录。至于方块,基于行来走,用3个对象来记录,走3行清空三个对象。

var isValidSudoku = function(board) {
    var row = {};
    var col = {};
    var suq = [{},{},{}];
    for (var i = 0;i<9;i++) {
        for (var j = 0; j < 9;j++) {
            var val = board[i][j];
            var valCol = board[j][i];
            console.log(i+":::"+valCol)
            if (valCol!=='.') {
                if (col[valCol]!==undefined) 
                    return false;
                else
                    col[valCol] = 0;
            }
            if (val!=='.') {
                //console.log(row[val])
                //行不重复
                if (row[val]!==undefined)
                    return false;
                else
                    row[val] = 0;
                //方块不重复
                if (suq[parseInt(j/3)][val]!==undefined)
                    return false;
                else
                    suq[parseInt(j/3)][val] = 0;
            }
        }
        row = {};
        col = {};
        if ((i%3)===2)
            suq = [{},{},{}];
    }
    return true;
};

你可能感兴趣的:(36. Valid Sudoku)