leetcode: 37. Sudoku Solver

来源:互联网 发布:深圳赛维网络ceo陈文平 编辑:程序博客网 时间:2024/06/06 02:21

Q

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.

Example

这里写图片描述

A sudoku puzzle…

这里写图片描述

…and its solution numbers marked in red.

AC

# Time:  ((9!)^9)# Space: (1)class Solution(object):    """    :type board: List[List[str]]    :rtype: void Do not return anything, modify board in-place instead.    """    def solveSudoku(self, board):        def isValid(board, x, y):            for k in xrange(9):                if (x != k and board[k][y] == board[x][y]) or (y != k and board[x][k] == board[x][y]):                    return False            for i in xrange(3*(x/3), 3*(x/3+1)):                for j in xrange(3*(y/3), 3*(y/3+1)):                    if (i != x or j != y) and board[i][j] == board[x][y]:                        return False            return True        def solver(board):            for i in xrange(9):                for j in xrange(9):                    if board[i][j] == '.':                        for k in xrange(9):                            board[i][j] = chr(ord('1')+k)                            if isValid(board, i, j) and solver(board):                                return True                            board[i][j] = '.'                        return False            return True        solver(board)if __name__ == '__main__':    board = [[".",".","9","7","4","8",".",".","."],             ["7",".",".",".",".",".",".",".","."],             [".","2",".","1",".","9",".",".","."],             [".",".","7",".",".",".","2","4","."],             [".","6","4",".","1",".","5","9","."],             [".","9","8",".",".",".","3",".","."],             [".",".",".","8",".","3",".","2","."],             [".",".",".",".",".",".",".",".","6"],             [".",".",".","2","7","5","9",".","."]]    Solution().solveSudoku(board)    assert board == [["5","1","9","7","4","8","6","3","2"],                     ["7","8","3","6","5","2","4","1","9"],                     ["4","2","6","1","3","9","8","7","5"],                     ["3","5","7","9","8","6","2","4","1"],                     ["2","6","4","3","1","7","5","9","8"],                     ["1","9","8","5","2","4","3","6","7"],                     ["9","7","5","8","6","3","1","2","4"],                     ["8","3","2","4","9","1","7","5","6"],                     ["6","4","1","2","7","5","9","8","3"]]


原创粉丝点击