DEV Community

Rakesh Reddy Peddamallu
Rakesh Reddy Peddamallu

Posted on

Leetcode - 36. Valid Sudoku

Javascript Code

/**
 * @param {character[][]} board
 * @return {boolean}
 */


const checkInRow = (i, j, board) => {
    let seen = new Set();
    for (let col = 0; col < 9; col++) {
        let num = board[i][col];
        if (num !== ".") {
            if (seen.has(num)) return false;
            seen.add(num);
        }
    }
    return true
}

const checkInColumn = (i, j, board) => {
    let seen = new Set();
    for (let row = 0; row < 9; row++) {
        let num = board[row][j];
        if (num !== ".") {

            if (seen.has(num)) return false;
            seen.add(num);
        }
    }
    return true
}


const checkInSquare = (i, j, board) => {
    let seen = new Set();

    let startRow = Math.floor(i / 3) * 3;
    let startCol = Math.floor(j / 3) * 3;

    for (let row = startRow; row < startRow + 3; row++) {
        for (let col = startCol; col < startCol + 3; col++) {
            let num = board[row][col];

            if (num !== ".") {
                if (seen.has(num)) return false;
                seen.add(num);
            }
        }
    }
    return true
}

var isValidSudoku = function (board) {

    for (let i = 0; i < 9; i++) {

        for (let j = 0; j < 9; j++) {

            if (board[i][j] !== ".") {
                if (!(checkInRow(i, j, board) && checkInColumn(i, j, board) && checkInSquare(i, j, board))) return false;
            }
        }
    }

    return true;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)