37. Sudoku Solver

这题难度为困难,目前通过率为32.2%

题目:

Write a program to solve a Sudoku puzzle by filling the empty cells.

A sudoku solution must satisfy all of the following rules:

1.Each of the digits 1-9 must occur exactly once in each row.
2.Each of the digits 1-9 must occur exactly once in each column.
3.Each of the the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.

Empty cells are indicated by the character ‘.’.

这里写图片描述

Note:

1.The given board contain only digits 1-9 and the character '.'.
2.You may assume that the given Sudoku puzzle will have a single unique solution.
3.The given board size is always 9x9.

题目是给出一个未填完的数独,需要用程序填满。

思路:
下面的代码主要使用了回溯法,当一个格子9次填数字都失败的时候,则返回上一个填的格子,试填下一个数字,直到9*9个格子全部填完。
判断方法仍然是三个数组,分别对应行、列和每个九宫格,当要填的数字与规则不冲突的时候,才能填进去并递归。

代码:

class Solution:
    def solveSudoku(self, board):
        self.board = board
        self.row = [[False for i in range(9)] for j in range(9)]
        self.col = [[False for i in range(9)] for j in range(9)]
        self.sqr = [[[False for i in range(9)] for j in range(3)] for k in range(3)]
        self.judge = False
        for i in range(9):
            for j in range(9):
                if self.board[i][j] != '.':
                    num = int(self.board[i][j]) - 1
                    self.row[i][num] = True
                    self.col[j][num] = True
                    self.sqr[i // 3][j // 3][num] = True
        self.solve(0,0)



    def solve(self,i,j):
        if i == 9:
            self.judge = True
            return

        if self.board[i][j] == '.':
            for k in range(9):
                if not(self.row[i][k] or self.col[j][k] or self.sqr[i//3][j//3][k]):
                    self.row[i][k] = True
                    self.col[j][k] = True
                    self.sqr[i // 3][j // 3][k] = True
                    self.board[i][j]=str(k+1)
                    if j==8 :
                        self.solve(i+1,0)
                    else:
                        self.solve(i,j+1)
                    if not self.judge:
                        self.row[i][k] = False
                        self.col[j][k] = False
                        self.sqr[i//3][j//3][k] = False
                        self.board[i][j] = "."
                    else:
                        return
        else:
            if j == 8:
                self.solve(i + 1, 0)
            else:
                self.solve(i, j + 1)
        return

复杂度分析:

由于使用了回溯法,因此难以判断算法复杂度。

提交:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值