码迷,mamicode.com
首页 > 其他好文 > 详细

037 Sudoku Solver

时间:2015-08-01 06:19:10      阅读:93      评论:0      收藏:0      [点我收藏+]

标签:

037 Sudoku Solver

这道题我纯暴力搜了 肯定可以优化, 懒得去看了。。。

class Solution:
    def __init__(self):
        self.b = []
    
    def solveSudoku(self, board):
        self.b = board[:]
        self.solve(0, 0)
        for i in range(0,9):
            for j in range(0,9):
                board[i][j] = self.b[i][j]
        

    def solve(self, i, j):
        if j >= 9:
            return self.solve(i+1, 0)
        if i == 9:
            return True
        if self.b[i][j] == .:
            for k in range(1, 10):
                self.b[i][j] = str(k)
                if self.isValid(i, j):
                    if self.solve(i, j+1):
                        return True
                self.b[i][j] = .
        else:
            return self.solve(i, j+1)
        return False

    def isValid(self, i, j):
        for k in range(0,9):
            if k != j and self.b[i][k] == self.b[i][j]:
                return False
            if k != i and self.b[k][j] == self.b[i][j]:
                return False
        for r in range(i/3*3, i/3*3+3):
            for c in range(j/3*3, j/3*3+3):
                if (r != i or c != j) and self.b[r][c] == self.b[i][j]:
                    return False
        return True
        

 

037 Sudoku Solver

标签:

原文地址:http://www.cnblogs.com/dapanshe/p/4693531.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!