LeetCode Training 36: Effective Sudoku

Keywords: network

Judge whether a 9x9 Sudoku is valid. Just verify the validity of the number that has been filled in according to the following rules.

Numbers 1-9 can only appear once per line.
Numbers 1-9 can only appear once in each column.
Numbers 1-9 can only appear once in each 3x3 uterus separated by a thick line.


The figure above is a partially filled valid Sudoku.

Numbers have been filled in some of the spaces in Sudoku. The blanks are represented by'.'.

Source: LeetCode
Link: https://leetcode-cn.com/problems/valid-sudoku
Copyright belongs to the seizure network. For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

1.

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        remain = []
        for i in range(9):
            remain.clear()
            for j in range(9):
                if board[i][j] == '.':
                    continue
                if board[i][j] not in remain:
                    remain.append(board[i][j])
                else:
                    return False
        for i in range(9):
            remain.clear()
            for j in range(9):
                if board[j][i] == '.':
                    continue
                if board[j][i] not in remain:
                    remain.append(board[j][i])
                else:
                    return False
        for x in range(0,9,3):
            for y in range(0,9,3):
                remain.clear()
                for i in range(3):
                    for j in range(3):
                        if board[x+i][y+j] == '.':
                            continue
                        if board[x+i][y+j] not in remain:
                            remain.append(board[x+i][y+j])
                        else:
                            return False
        return True
                        
                

 2.

class Solution:
    def isValidSudoku(self, board: list) -> bool:
        remain1 = []
        remain2 = []
        remain3 = []
        for a in range(9):
            remain3.append([])
        for i in range(9):
            remain1.clear()
            remain2.clear()
            for j in range(9):
                if board[i][j] != '.':
                    if board[i][j] in remain1:
                        return False
                    else:remain1.append(board[i][j])
                    if board[i][j] in remain3[(i//3)*3+(j//3)]:
                        return False
                    else:remain3[(i//3)*3+(j//3)].append(board[i][j])
                if board[j][i] != '.':
                    if board[j][i] in remain2:
                        return False
                    else:remain2.append(board[j][i])
        return True

 

Posted by MarCn on Wed, 09 Oct 2019 02:31:45 -0700