python解数独
Posted 米意思
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python解数独相关的知识,希望对你有一定的参考价值。
昨晚心血来潮在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解数独的主要内容,如果未能解决你的问题,请参考以下文章