Sudoku Solver

Posted Sheryl Wang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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.

这题是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的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 37 Sudoku Solver(求解数独)

37. Sudoku Solver

Sudoku Solver & Valid Sudoku

Sudoku Solver

037. Sudoku Solver

java 37. Sudoku Solver(#)。java