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

Sudoku Solver

时间:2016-08-29 22:35:32      阅读:239      评论:0      收藏:0      [点我收藏+]

标签:

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.

这题是Valid Sudoku的follow up。

思路还是DFS,需要注意的是如何check,需要每添加一个元素就检查当前元素所处的行和列,和其所在的3*3的小分块,如果没有冲突则继续。否则重新置为‘.’。值得注意的是可能因为之前的选择不对,会遇到当前‘.‘枚举所有元素都不合格的情况,此处会不断返回False,backtrack将之前所有加的点都弹出。

代码如下:

class Solution(object):
    def solveSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        if not board or len(board)!= 9 or len(board[0]) != 9:
            return 
        
        self.helper(board,0,0)
        return 
    def helper(self, board, i, j):   #i,j is the index of current position
        if j >= 9:
            return self.helper(board, i+1, 0)
        if i == 9:
            return True 
        if board[i][j] == .:
            for k in xrange(1,10):
                board[i][j] = str(k)
                if self.isValid(board, i, j):
                    if self.helper(board, i, j+1):
                        return True
                board[i][j] = .
        else:
            return self.helper(board, i, j+1)
        return False
    def isValid(self, board, i, j):
        for k in xrange(9):
            if k != j and board[i][k] == board[i][j]:
                return False
        for k in xrange(9):
            if k != i and board[k][j] == board[i][j]:
                return False
        for row in xrange(i/3*3, i/3*3+3):
            for col in xrange(j/3*3, j/3*3+3):
                if (row != i or col != j) and board[row][col] == board[i][j]:
                    return False
        return True

 

Sudoku Solver

标签:

原文地址:http://www.cnblogs.com/sherylwang/p/5819725.html

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