[Leetcode]36. Valid Sudoku@python

题目

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.

题目要求

判断一个数独的例子是否满足数独的要求:
1. 每行出现数字1-9一次且仅一次
2. 每列出现数字1-9一次切仅一次
3. 上图示例中粗线划出的每三行三列的block中出现数字1-9一次且仅以此

解题思路

  1. 参考南郭子綦.
  2. 自己实现的检验方法,看起来没有那么优美

代码

  • 解法1
class Solution(object):
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        def isValid(x,y,tmp):
            for i in range(9):
                if board[i][y] == tmp: return False
            for j in range(9):
                if board[x][j] == tmp: return False

            for i in range(3):
                for j in range(3):
                    if board[(x/3)*3 + i][(y/3)*3 + j] == tmp:
                        return False
            return True

        for i in range(9):
            for j in range(9):
                if board[i][j] == '.': continue
                tmp = board[i][j]
                board[i][j] = 'D'
                if isValid(i,j,tmp) == False: return False
                board[i][j] = tmp
        return True
  • 解法2
class Solution(object):
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        for i in range(9):
            rowMap = {}
            colMap = {}

            for j in range(9):
                # check if row valid
                if board[i][j] not in rowMap:
                    rowMap[board[i][j]] = 1
                else:
                    rowMap[board[i][j]] += 1
                    if rowMap[board[i][j]] > 1 and board[i][j] != '.':
                        return False
                # check if col valid
                if board[j][i] not in colMap:
                    colMap[board[j][i]] = 1
                else:
                    colMap[board[j][i]] += 1
                    if colMap[board[j][i]] > 1 and board[j][i] != '.':
                        return False
                # check if block valid
                if i % 3 == 0 and j % 3 == 0:
                    blockMap = {}
                    for s in range(3):
                        for t in range(3):
                            if board[i + s][j + t] not in blockMap:
                                blockMap[board[i+s][j+t]] = 1
                            else:
                                blockMap[board[i+s][j+t]] += 1
                                if blockMap[board[i+s][j+t]] > 1 and board[i+s][j+t] != '.':
                                    return False
        return True

你可能感兴趣的:(Leetcode,leetcode)