Valid Sudoku

Problem Id: 36 Difficulty: Medium Tag: Hash Table


Intuition

This is a simple problem. But the implementation is not short.

Solution


class Solution:
    def isValidSudoku(self, board):
        # Valid Row
        for x in range(9):
            exist = set()
            for y in range(9):
                if board[x][y] == '.':
                    continue
                if board[x][y] in exist:
                    return False
                exist.add(board[x][y])

        # Valid Column
        for y in range(9):
            exist = set()
            for x in range(9):
                if board[x][y] == '.':
                    continue
                if board[x][y] in exist:
                    return False
                exist.add(board[x][y])

        # Valid sub board
        for x_offset in range(0, 9, 3):
            for y_offset in range(0, 9, 3):
                exist = set()
                for x in range(x_offset, x_offset + 3):
                    for y in range(y_offset, y_offset + 3):
                        if board[x][y] == '.':
                            continue
                        if board[x][y] in exist:
                            return False
                        exist.add(board[x][y])

        return True