【LeetCode题意分析&解答】36. Valid Sudoku

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.

题意分析:

  本题是验证一个数独(不一定是完整的,空白的元素用"."来代替)是否是正确的。

  先来看一下数独的规则:

There are just 3 rules to Sudoku.

Each row must have the numbers 1-9 occuring just once.
Each column must have the numbers 1-9 occuring just once.
And the numbers 1-9 must occur just once in each of the 9 sub-boxes of the grid.

  很容易得到3个规则:

  1. 每一行只能出现1~9一次;
  2. 每一列只能出现1~9一次;
  3. 每个3×3子区域只能出现1~9一次(子区域之间没有交叉,也就是一共有9个子区域

解答:

  本题直接根据数独的规则“翻译”成代码就可以了:可以设3个长度为9的List,分别代表行、列、子区域。循环每个元素查看是否在相应的List中,如果存在说明重复,不符合规则;如果不存在就把当前元素加入到该List中。如果所有元素循环完毕,说明没有重复值,返回True。该题可以假设输入均合法,即都是1~9或"."。

AC代码:

class Solution(object):
    def isValidSudoku(self, board):
        row = [[] for _ in xrange(9)]
        col = [[] for _ in xrange(9)]
        area = [[] for _ in xrange(9)]
        for i in xrange(9):
            for j in xrange(9):
                element = board[i][j]
                if element != '.':
                    # calculate every sub-boxes, map to the left top element
                    area_left_top_id = i / 3 * 3 + j / 3
                    if element in row[i] or element in col[j] or element in area[area_left_top_id]:
                        return False
                    else:
                        row[i].append(element)
                        col[j].append(element)
                        area[area_left_top_id].append(element)
        return True

 

你可能感兴趣的:(【LeetCode题意分析&解答】36. Valid Sudoku)