python leetcode 37. Sudoku Solver

有效数独的进阶版,DFS一个个数字尝试取再设置一个标志位flag=[]退出

class Solution:
    def solveSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        dict1={}
        q=[]
        for i in range(9):
            for j in range(9):
                if board[i][j]!='.':
                    d=int(board[i][j])
                    dict1[(i,-1,d)]=True
                    dict1[(-1,j,d)]=True
                    dict1[(i//3,j//3,d)]=True
                else:
                    q.append((i,j))
        flag=[False]
        def dfs(board,index,q,dict1):
            if index==len(q): 
                flag[0]=True 
                return 
            i,j=q[index][0],q[index][1]
            for d in range(1,10):
                if (i,-1,d) in dict1 or (-1,j,d) in dict1 or (i//3,j//3,d) in dict1:
                    continue 
                else:
                    board[i][j]=str(d)
                    dict1[(i,-1,d)]=True
                    dict1[(-1,j,d)]=True
                    dict1[(i//3,j//3,d)]=True
                    dfs(board,index+1,q,dict1)
                    if flag[0]: return 
            i,j=q[index-1][0],q[index-1][1]
            d=int(board[i][j])
            del dict1[(i,-1,d)]
            del dict1[(-1,j,d)]
            del dict1[(i//3,j//3,d)] 
            board[i][j]='.'
        dfs(board,0,q,dict1)
展开阅读全文

没有更多推荐了,返回首页