回溯算法-解数独

假设-判断-假设


class solution():

    def solve(self,arr):
        self.helper(arr,0)

    def helper(self,arr,index):
        if index==81:
            print(arr)
            return
        else:
            if arr[index]==0:# 0代表需要填充数据
                for i in range(1,10):
                    if self.isVaild(arr,index,i):
                        arr[index]=i
                        self.helper(arr,index+1)
                        arr[index]=0# 如果假设下一个格子失败就将本次的假设取消。
            else:
                self.helper(arr,index+1)


    def isVaild(self,arr,index,i):
        line = index//9
        column = index % 9
        if i in arr[line*9:line*9+9]:# 判断这一行
            return False
        if i in [arr[j] for j in range(len(arr)) if j%9==column]:# 判断这一列
            return False
        for l in range(line//3*3,line//3*3+3): # 判断这个九宫格内
            for c in range(column//3*3,column//3*3+3):
                if arr[l*9+c]==i:
                    return False
        return True


if __name__ == '__main__':
    arr = [
        4,1,0,0,0,7,8,5,0,
        8,0,6,0,0,0,0,0,9,
        0,2,0,0,9,0,6,0,0,
        0,0,4,0,0,0,0,1,2,
        2,0,0,5,8,0,0,7,0,
        0,0,0,0,0,0,5,0,0,
        0,0,0,7,0,2,0,0,0,
        0,0,8,0,1,0,0,0,0,
        0,7,0,0,6,0,0,0,0,
    ]
    arr = [
        0,6,4,1,0,9,3,0,0,
        0,3,0,0,0,0,7,0,0,
        0,0,1,0,0,2,0,0,0,
        3,0,9,7,4,5,0,0,0,
        6,4,8,0,1,0,5,2,7,
        0,5,0,0,8,0,0,3,0,
        7,8,5,3,2,4,1,0,6,
        2,9,5,8,5,0,0,7,0,
        4,1,0,6,9,0,2,0,8
    ]
    my_solution = solution()
    my_solution.solve(arr)






你可能感兴趣的:(算法)