【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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM