LintCode:判断数独是否合法

LintCode:判断数独是否合法

数独合法并不一定有解,只需要依次判断每行、每列、每个九宫格是否存在重复数字即可。

class Solution:
    # @param board, a 9x9 2D array
    # @return a boolean
    def isValidSudoku(self, board):
        for i in range(9):
            L = []  #每行
            M = []  #第列
            for j in range(9):
                if board[i][j] in L:
                    return False
                elif board[i][j] != '.':
                    L.append(board[i][j])
                if board[j][i] in M:
                    return False
                elif board[j][i] != '.':
                    M.append(board[j][i])
        m = 0
        n = 0
        while m < 9:
            while n < 9:
                L = []  #每个九宫格
                for i in range(m, m+3):
                    for j in range(n, n+3):
                        if board[i][j] in L:
                            return False
                        elif board[i][j] != '.':
                            L.append(board[i][j])
                n += 3
            m += 3
        return True

你可能感兴趣的:(lintcode,python)