[LeetCode] 36. Valid Sudoku

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

题目

Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.
  2. Each column must contain the digits 1-9 without repetition.
  3. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

九宫格
A partially filled sudoku which is valid.

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

Example 1:

Input:
[
  ["5","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]
Output: true

Example 2:

Input:
[
  ["8","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]
Output: false

Explanation: Same as Example 1, except with the 5 in the top left corner being
modified to 8. Since there are two 8’s in the top left 3x3 sub-box, it is invalid.
Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.
  • The given board contain only digits 1-9 and the character ‘.’.
  • The given board size is always 9x9.

思路

题目大意

检查九宫格是否可用。3个检查项:
1. 每行不能有重复的元素。
2. 每列不能有重复的元素。
3. 每个小三宫格中不能有重复的元素。

解题思路

建立 对应的 三种 map。记录每行、每列、每个小宫格的是否有重复。

code

from collections import defaultdict

class Solution:
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        m1diclst = [defaultdict(lambda :False) for i in range(9)] 
        m2diclst = [defaultdict(lambda :False) for i in range(9)] 
        m3diclst = [defaultdict(lambda :False) for i in range(9)] 

        for i in range(9):
            for j in range(9):
                if board[i][j] != '.':
                    if m1diclst[i][board[i][j]]:
                        return False
                    m1diclst[i][board[i][j]] = True

                    if m2diclst[j][board[i][j]]:
                        return False
                    m2diclst[j][board[i][j]] = True

                    if m3diclst[i//3*3+j//3][board[i][j]]:
                        return False
                    m3diclst[i//3*3+j//3][board[i][j]] = True
        return True

猜你喜欢

转载自blog.csdn.net/u013383813/article/details/82589708