Valid Sudoku

Question

Determine whether a Sudoku is valid.

The Sudoku board could be partially filled, where empty cells are filled with the character .

img

Thoughts

only check filled one

valid conditions:

  • row contains 1-9, no duplicate
  • column contains 1-9, no dup
  • sub sudoku contains 1-9, no dup

Solution

class Solution:
    # @param board, a 9x9 2D array
    # @return a boolean
    def isValidSudoku(self, board):
        length = 9
        if len(board) != length:
            return False
        rowValid = [[False for i in range(length)] for j in range(length)]
        colValid = [[False for i in range(length)] for j in range(length)]
        subValid = [[False for i in range(length)] for j in range(length)]


        for row in range(length):
            for col in range(length):
                if board[row][col] == ".":
                    continue
                val = int(board[row][col]) - 1
                if rowValid[row][val]:
                    return False
                if colValid[col][val]:
                    return False
                if subValid[(row/3)*3+col/3][val]:
                    return False

                rowValid[row][val] = True
                colValid[col][val] = True
                subValid[(row/3)*3+col/3][val] = True

        return True