leetcode 36. 有效的數獨

因爲工做緣由,之後A題通常都使用Python,不得不說Python還挺方便的,做爲一個腳本語言學好了,會省不少事情。this

判斷一個 9x9 的數獨是否有效。只須要根據如下規則,驗證已經填入的數字是否有效便可。spa

  1. 數字 1-9 在每一行只能出現一次。
  2. 數字 1-9 在每一列只能出現一次。
  3. 數字 1-9 在每個以粗實線分隔的 3x3 宮內只能出現一次。

Code 1:code

class Solution:
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """

        for i in range(9):
            for j in range(9):
                if board[i][j] == '.':
                    board[i][j] = 0
                else :
                    board[i][j] = int(board[i][j])


        flag = [0] * 10
        ans = True
        for i in range(9):
            flag = [0] * 10
            for j in range(9):
                if board[i][j] == 0:
                    continue
                flag[board[i][j]]+=1
                if flag[board[i][j]] > 1:
                    ans = False


        flag = [0] * 10

        for j in range(9):
            flag = [0] * 10
            for i in range(9):
                if board[i][j] == 0:
                    continue
                flag[board[i][j]] +=1
                if flag[board[i][j]] > 1:
                    ans = False


        for i in range(0,9,3):
            for j in range(0,9,3):
                flag = [0]*10
                for m in range(3):
                    for n in range(3):
                        if board[i+m][j+n] == 0:
                            continue
                        flag[board[i+m][j+n]] +=1
                        if flag[board[i+m][j+n]] > 1:
                            ans = False

        return ans

Code : 2blog

  • 根據行列,能夠獲得子數獨的索引 (row // 3) * 3 + col // 3
  • Python字典,d.get(key, default) ,當沒有這個鍵,或者鍵沒有值時,使用get方法返回默認值,不然出錯。
class Solution:
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        # init data
        rows = [{} for i in range(9)]
        columns = [{} for i in range(9)]
        boxes = [{} for i in range(9)]

        # validate a board
        for i in range(9):
            for j in range(9):
                num = board[i][j]
                if num != '.':
                    num = int(num)
                    box_index = (i // 3) * 3 + j // 3

                    rows[i][num] = rows[i].get(num, 0) + 1
                    columns[j][num] = columns[j].get(num, 0) + 1
                    boxes[box_index][num] = boxes[box_index].get(num, 0) + 1

                    # check if this value has been already seen before
                    if rows[i][num] > 1 or columns[j][num] > 1 or boxes[box_index][num] > 1:
                        return False
        return True
相關文章
相關標籤/搜索