【LeetCode】36. 有效的数独

题目描述(中等难度)

【LeetCode】36. 有效的数独_第1张图片
【LeetCode】36. 有效的数独_第2张图片
【LeetCode】36. 有效的数独_第3张图片

解题思路

【LeetCode】36. 有效的数独_第4张图片


class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        # 判断每一行
        for i in range(9):
            if not self.isValidRows(board[i]):
                return False
        # 判断每一列
        for i in range(9):
            if not self.isValidCols(i, board):
                return False
        # 判断每个小棋盘
        for i in range(0,9,3):
            for j in range(0,9,3):
                if not self.isValidSmall(i, j, board):
                    return False
        return True
    
    def isValidRows(self,board):
        res = {}
        for i in board:
            if i !=".":
                if res.get(i,0) != 0:
                    return False
                else:
                    res[i] = 1
        return True
    
    def isValidCols(self,i,board):
        res = {}
        for j in range(9):
            if board[j][i] != ".":
                if res.get(board[j][i],0) != 0:
                    return False
                else:
                    res[board[j][i]] = 1
        return True

    def isValidSmall(self,i,j,board):
        res = {}
        for m in range(i,i+3):
            for n in range(j,j+3):
                if board[m][n] != ".":
                    if res.get(board[m][n],0) != 0:
                        return False
                    else:
                        res[board[m][n]] = 1
        return True

【LeetCode】36. 有效的数独_第5张图片

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        a = set()
        for i in range(9):
            for j in range(9):
                number = board[i][j]
                if number != ".":
                    if (number + " in row " + str(i)) in a or (number + " in column " + str(j)) in a or (number + " in block " + str(i//3) + "-" + str(j//3)) in a:
                        return False
                    else:
                        a.add(number + " in row " + str(i))
                        a.add(number + " in column " + str(j))
                        a.add(number + " in block " + str(i//3) + "-" + str(j//3))
        return True


解法三
【LeetCode】36. 有效的数独_第6张图片

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        row = [{} for i in range(9)]
        col = [{} for i in range(9)]
        box = [{} for i in range(9)]
        for i in range(9):
            for j in range(9):
                num = board[i][j]
                boxindex = (i//3)*3 + j//3
                if num != ".":
                    row[i][num] = row[i].get(num,0) + 1
                    col[j][num] = col[j].get(num,0) + 1
                    box[boxindex][num] = box[boxindex].get(num,0) + 1
                    if row[i][num] > 1 or col[j][num] > 1 or box[boxindex][num] > 1:
                        return False
        return True

你可能感兴趣的:(数据结构与算法)