LeetCode解题笔记37 Sudoku Solver

题目:

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

Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.


A sudoku puzzle...


...and its solution numbers marked in red.


python解法一:

思路:采用深度优先算法,每填入一个数字都判断该数字是否是合法的。由于之前填入的数字都已判断过,所以不需要进行冗余的判断整个数组是否是合法的。

class Solution:
    def isValidSudoku(self, board, i, j):
        for m in range(len(board[i])):
            if m!=j and board[i][j]==board[i][m]:
                return False
        for n in range(len(board)):
            if n!=i and board[i][j]==board[n][j]:
                return False
        for m in range(i//3*3,i//3*3+3):
            for n in range(j//3*3,j//3*3+3):
                if (m!=i and n!=j) and board[i][j]==board[m][n]:
                    return False
        return True

    def solveSudokuDFS(self, board, i, j):
        if i==9:
            return True
        if j>=9:
            return self.solveSudokuDFS(board,i+1,0)
        if board[i][j]==".":
            for k in ["1","2","3","4","5","6","7","8","9"]:
                board[i][j] = k
                if self.isValidSudoku(board,i,j):
                    if self.solveSudokuDFS(board,i,j+1):
                        return True
                board[i][j] = "."
        else :
            return self.solveSudokuDFS(board,i,j+1)
        


    def solveSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        self.solveSudokuDFS(board, 0, 0)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值