码迷,mamicode.com
首页 > 编程语言 > 详细

python解数独

时间:2016-06-15 15:34:49      阅读:296      评论:0      收藏:0      [点我收藏+]

标签:

昨晚心血来潮在leetcode上pick one了一道算法题

https://leetcode.com/problems/sudoku-solver/

解决代码如下:

class Solution(object):
    def solveSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: void Do not return anything, modify board in-place instead.
        """
        def check(i, j, value):
            for item in board[i]:
                if item == value:
                    return False
            for item in board:
                if item[j] == value:
                    return False
            col, row = i/3*3, j/3*3
            array = board[col][row:row+3] + board[col+1][row:row+3] + board[col+2][row:row+3]
            for item in array:
                if item == value:
                    return False
            return True
        def get_next(i, j): 
            for row in range(j+1, 9): 
                if board[i][row] == ".":
                    return i, row 
            for col in range(i+1, 9): 
                for row in range(9):
                    if board[col][row] == ".":
                        return col, row 
            return -1, -1
        def try_num(i, j): 
            if board[i][j] == ".":
                for num in range(1, 10):
                    if check(i, j, str(num)):
                        board[i][j] = str(num)
                        next_i, next_j = get_next(i, j)
                        if next_i == -1: 
                            return True
                        else:
                            end = try_num(next_i, next_j)
                            if not end:
                                board[i][j] = "."
                            else:
                                return True
        if board[0][0] == ".":
            try_num(0, 0)
        else:
            i, j = get_next(0, 0)
            try_num(i, j)
        return

主要使用回溯递归的方法,先定义一个判断函数和一个获得下一个位置的函数,使结构清晰一些。

然后对可选i,j进行1~9遍历,如果遍历成功,获得next_i, next_j进行下一轮遍历,如果失败则重置为"."

思路还是挺好理解的,代码beat了60%,不知道为什么这个题设为hard了,以前设计过数独的题,这次解数独题也不是什么难事了。

 

突然想起来test case给的是

["..9748...","7........",".2.1.9...","..7...24.",".64.1.59.",".98...3..","...8.3.2.","........6","...2759.."]

实际给的是

[[‘.‘, ‘.‘, ‘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‘, ‘.‘, ‘.‘]]

自己测试的时候别弄混了

python解数独

标签:

原文地址:http://www.cnblogs.com/miyisia/p/5587476.html

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