leetcode--37. 解数独

题目:leetcode--37. 解数独

链接:https://leetcode-cn.com/problems/sudoku-solver/description/

解数独,初始残局用 “ . ”表示空白格。以前考研那时候写过C语言的,递归求解。现在要在实参基础上改,不要返回结果,这样的话DFS加一个返回值判断就好了,当找到解的时候返回True,不再回溯。

python:

def isRowAndColValid(x, y, field, num):
    for i in range(9):
        if field[x][i] == str(num):
            return False
    for j in range(9):
        if field[j][y] == str(num):
            return False
    return True

def isSquareValid(x, y, field, num):
    row, col = (x // 3) * 3, (y // 3) * 3
    for i in range(row, row + 3):
        for j in range(col, col + 3):
            if field[i][j] == str(num):
                return False
    return True

def getNext(field):
    for x in range(9):
        for y in range(9):
            if field[x][y] == ".":
                return [x, y]
    return []

class Solution:
    def solveSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        def DFS(board):
            next = getNext(board)
            if not next:
                # print(board)
                return True
            for i in range(1, 10):
                if isRowAndColValid(next[0], next[1], board, i) and isSquareValid(next[0], next[1], board, i):
                    board[next[0]][next[1]] = str(i)
                    if DFS(board):
                        return True
                    board[next[0]][next[1]] = "."
        DFS(board)

你可能感兴趣的:(leetcode)