Leetcode: Valid Sudoku

Question

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.

Hide Tags Hash Table

Analysis

check every row, col and 3×3 grids.

Solution

class Solution:
    # @param {character[][]} board
    # @return {boolean}
    def isValidSudoku(self, board):
        n = len(board)
        for row in range(n/3):
            for col in range(n/3):
                array = []
                temp = board[row*3:row*3+3]
                for i in range(3):
                    array += temp[i][col*3:col*3+3]
                if not self.helper(array):
                    return False

        for row in range(n):
            if not self.helper(board[row]):
                return False

        for col in range(n):
            array = []
            for row in range(n):
                array += [ board[row][col] ]
            if not self.helper(array):
                return False

        return True



    def helper(self, array):
        dict = {}
        for val in array:
            if val!='.':
                if val in dict:
                    return False
                else:
                    dict[val] = val

        return True


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