题解 | #Sudoku#

Sudoku

http://www.nowcoder.com/practice/78a1a4ebe8a34c93aac006c44f6bf8a1

DFS


class Solution:
    def getAns(self, board):
        def dfs(pos):
            nonlocal valid
            if pos == len(spaces):
                valid = True
                return
            i, j = spaces[pos]
            for digit in range(9):
                if line[i][digit] == column[j][digit]==block[i // 3][j // 3][digit] == False:
                    line[i][digit] = column[j][digit]= block[i // 3][j // 3][digit] = True
                    board[i][j] = str(digit+1)
                    dfs(pos + 1)
                    line[i][digit] = column[j][digit]=block[i // 3][j // 3][digit] = False
                if valid:
                    return
        line = [[False]*9 for _ in range(9)]
        column = [[False]*9 for _ in range(9)]
        block = [[[False]*9 for _ in range(3)] for __ in range(3)]
        valid = False
        spaces= []
        for i in range(9):
            for j in range(9):
                if board[i][j] == '0':
                    spaces.append((i,j))
                else:
                    digit = int(board[i][j]) - 1
                    line[i][digit] = column[j][digit]=block[i // 3][j // 3][digit] = True
        dfs(0)

while True:
    try:
        board = []
        for i in range(9):
            board.append(input().split())
        test = Solution()
        test.getAns(board)
        for i in range(9):
            print(" ".join(board[i]))
    except:
        break
        
全部评论

相关推荐

09-08 17:17
同济大学 Java
狗不理fe:里面的人劝一句,别来虾,我们部门24校招生淘汰率30%,还有一些人说有一年保护期,不可能!!!
我的秋招日记
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务