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

相关推荐

浪子陪都:简历最优秀的地方放到了后面,国奖,校级奖学金这些是最亮眼的。说明你跟同级别的学生不一样。 建议台灯这个,PCB布局布线这个词汇不专业,业内是PCB Layout,第二,单片机的板子一般不用考虑SI,PI 都是低速信号,只要遵循3W原则就好了。 单片机的项目太low了,技能这块,你要看一下BOSS直聘的招聘要求,按照别人的要求写,一些关键词可以增加你简历被检索到的概率。 主修课程不用写,这个没有人去关注的。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务