Skip to content

36. Valid Sudoku

https://leetcode.com/problems/valid-sudoku/

js
/**
 * @param {character[][]} board
 * @return {boolean}
 */
var isValidSudoku = function(board) {
  function valid(nums) {
    nums = nums.filter(x => x !== '.')
    return new Set(nums).size === nums.length
  }

  for (let i = 0; i < 9; i++) {
    if (!valid(board[i])) {
      return false
    }
  }

  for (let i = 0; i < 9; i++) {
    let nums = []
    for (let j = 0; j < 9; j++) {
      nums.push(board[j][i])
    }
    if (!valid(nums)) {
      return false
    }
  }

  for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
      let nums = board[j * 3].slice(i * 3, i * 3 + 3)
        .concat(board[j * 3 + 1].slice(i * 3, i * 3 + 3))
        .concat(board[j * 3 + 2].slice(i * 3, i * 3 + 3))
      if (!valid(nums)) {
        return false
      }
    }
  }

  return true
}
py
class Solution(object):

    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        for i in range(9):
            if not self.valid([board[i][j] for j in range(9)]) or not self.valid([board[j][i] for j in range(9)]):
                return False

        for i in range(3):
            for j in range(3):
                if not self.valid([board[m][n] for n in range(3 * j, 3 * j + 3) for m in range(3 * i, 3 * i + 3)]):
                    return False

        return True

    def valid(self, nums):
        nums = filter(lambda x: x != '.', nums)
        return len(set(nums)) == len(nums)