leetcode buckle 36. The effective force of Sudoku

Determining a number of unique 9x9 is valid. Only according to the following rules, to verify whether the numbers already filled can be effective.

The numbers 1-9 appear only once in each row.
The numbers 1-9 appear only once in each column.
Figures 1-9 only appear once in each 3x3 intrauterine separated by a thick solid line.


The figure is the number of valid only a partially filled.

Sudoku part of this space has been filled in the numbers, empty cells with '.' Representation.

Example 1:

输入:
[
  ["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"]
]
输出: true
示例 2:
















Only a valid number (portion has been filled) is not necessarily solvable.
According to the above rules only need to verify whether the figures have been filled can be effective.
Given the number of unique sequence comprises only numeric characters 1-9 and '.'.
Sudoku will always be given in the form of 9x9.

class Solution(object):
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        #首先初始化
        rows = [{} for i in range(9)]
        cols = [{} for i in range(9)]
        areas = [{} for i in range(9)]
        #遍历
        for i in range(9):
            for j in range(9):
                num = board[i][j]
                if(num!='.'):
                    #赋值
                    index = (i//3)*3+j//3
                    rows[i][num] = rows[i].get(num,0)+1
                    cols[j][num] = cols[j].get(num,0)+1
                    areas[index][num] = areas[index].get(num,0)+1
        #判断是否合规
                    if rows[i][num]>1 or cols[j][num]>1 or areas[index][num]>1:
                        return False
        return True

 

Published 292 original articles · won praise 160 · views 480 000 +

Guess you like

Origin blog.csdn.net/qq_32146369/article/details/104071547