Leetcode 37. Sudoku Solver

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

A sudoku solution must satisfy all of the following rules:

Each of the digits 1-9 must occur exactly once in each row.
Each of the digits 1-9 must occur exactly once in each column.
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 ‘.’.

1. 思路

题目意思就是给了一个数独盘,要求完成数独游戏,条件和上一题一样,行列都需要包含1-9,不重复

采用回溯法即可,满足条件往下走,不满足的情况回溯,
可以直接将36题的函数拿过来用,不过为了节省内存,进行一些改动

2.Code

class Solution:
    def __init__(self):
        self.board = None

    def find_unassign(self):
        for row in range(9):
            for col in range(9):
                if self.board[row][col] == '.':
                    return row, col
        return -1, -1

    # 验证行
    def row_valid(self, row, cur):
        for col in range(9):
            if self.board[row][col] == cur:
                return False
        return True

    # 验证列
    def col_valid(self, col, cur):
        for row in range(9):
            if self.board[row][col] == cur:
                return False
        return True

    # 验证3x3小方格
    def cell_valid(self, row, col, cur):
        for i in range(row, row + 3):
            for j in range(col, col + 3):
                if self.board[i][j] == cur:
                    return False
        return True

    # 判断当前填入的数是否满足
    def cur_valid(self, row, col, cur):
        start_row = row - row % 3
        start_col = col - col % 3
        if self.row_valid(row, cur) and self.col_valid(col, cur) and self.cell_valid(start_row, start_col, cur):
            return True
        return False

    # 递归回溯
    def solve(self):
        row, col = self.find_unassign()
        # 递归出口,完成数独
        if row == -1 and col == -1:
            return True
        for num in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
            if self.cur_valid(row, col, num):
                self.board[row][col] = num
                if self.solve():
                    return True
                self.board[row][col] = '.'
        return False

    def solveSudoku(self, board):
        self.board = board
        self.solve()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值