题解 | #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
        
全部评论

相关推荐

04-29 18:07
常州大学 Java
寂静羽翼:兄弟我已经亲身经历了,双非没实习很多大厂还是会给笔试的,可是有的公司笔试做的好也不给面一直卡着,ssob基本看我没实习都拒绝我了,但是每天投满偶尔也能有一两场初创公司的面试,但是薪资基本在五六千
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务