Environment: Python27

# -*- coding: UTF-8 -*-
'''
Created on 2017年6月9日 @author: LXu4
'''
import copy
import time
class Soduku(object):
def __init__(self, problem):
self.problem = problem def resolve(self):
solutionStack = [self.problem]
tmp = self.get_solution_array(self.problem)
solutionArrayStack = [tmp]
time_t = 0
prev_x = -1
prev_y = -1
while 1:
# time_t += 1
# fetch the last solution in solution stack
next_item_cord = {}
solutionArray = []
# print 'still ',len(solutionStack),'in stack'
solutionNow = copy.deepcopy(solutionStack[len(solutionStack) - 1])
solutionArray = solutionArrayStack[len(solutionArrayStack) - 1] flag = self.check_if_need_to_back(solutionNow, solutionArray)
if flag is True:
# print 'pop!'
solutionArrayStack.pop()
solutionStack.pop()
else:
time_t += 1
# next_item_cord = self.get_first_possible_item(solutionArray,solutionNow=solutionNow)
next_item_cord = self.get_first_possible_item(solutionArray,solutionNow=solutionNow)
if next_item_cord == False:
break
# print 'next_item_cord:',next_item_cord
prev_x = next_item_cord['x']
prev_y = next_item_cord['y']
next_item_array = solutionArray[prev_x][prev_y]
next_item = next_item_array[len(next_item_array)-1]
# randint(0,len(next_item_array)-1)
solutionNow[prev_x][prev_y] = next_item # solutionArray_tmp = get_solution_array(solutionNow)
solutionArray_tmp = copy.deepcopy(solutionArray)
solutionArray_tmp = self.get_resolution_array_new(solutionArray_tmp, prev_x, prev_y,
next_item)
if next_item in solutionArray[prev_x][prev_y]:
solutionArray[prev_x][prev_y].remove(
next_item)
# print 'next point is ',prev_x,',',prev_y
solutionStack.append(solutionNow)
solutionArrayStack.append(solutionArray_tmp)
# print solutionArrayStack
# print solutionStack for i in range(0, 9, 1):
print solutionStack[len(solutionStack) - 1][i]
print 'total forward:',time_t def check_if_need_to_back(self,solutionNow, solutionArray):
for i in range(0, 9, 1):
for j in range(0, 9, 1):
if len(solutionArray[i][j]) == 0 and solutionNow[i][j] == 0:
return True
return False def get_resolution_array_new(self,solutionArray, x, y, value):
for tmp_j in range(0, 9, 1):
if value in solutionArray[x][tmp_j]:
solutionArray[x][tmp_j].remove(value)
for tmp_i in range(0, 9, 1):
if value in solutionArray[tmp_i][y]:
solutionArray[tmp_i][y].remove(value)
for tmp_i in range(x / 3 * 3, x / 3 * 3 + 3):
for tmp_j in range(y / 3 * 3, y / 3 * 3 + 3):
if value in solutionArray[tmp_i][tmp_j]:
solutionArray[tmp_i][tmp_j].remove(value)
return solutionArray def get_solution_array(self,problem):
tmp = []
for i in range(0, 9, 1):
tmp_line_array = []
for j in range(0, 9, 1):
# print '['+bytes(i)+','+bytes(j)+']: '+ bytes(problem[i][j])
if problem[i][j] == 0:
# no value, get possible value array
tmp_value = [1, 2, 3, 4, 5, 6, 7, 8, 9] # remove the existed value in line
for tmp_j in range(0, 9, 1):
if problem[i][tmp_j] != 0:
if problem[i][tmp_j] in tmp_value:
tmp_value.remove(problem[i][tmp_j]) # remove the existed value in column
for tmp_i in range(0, 9, 1):
if problem[tmp_i][j] != 0:
if problem[tmp_i][j] in tmp_value:
tmp_value.remove(problem[tmp_i][j]) # remove the existed value in the rectangle
for x in range(i / 3 * 3, i / 3 * 3 + 3):
for y in range(j / 3 * 3, j / 3 * 3 + 3):
if problem[x][y] != 0:
if problem[x][y] in tmp_value:
tmp_value.remove(problem[x][y]) tmp_line_array.append(tmp_value)
else:
tmp_line_array.append([])
tmp.append(tmp_line_array)
# print tmp_line_array
# print tmp
return tmp # get first item to be the point of tree
def get_first_possible_item(self, solution_array, solutionNow = None):
is_finished = True
shortest_item_length = 9
shortest_item_x = 0
shortest_item_y = 0
for i in range(0, 9, 1):
for j in range(0, 9, 1):
tmp_length = len(solution_array[i][j])
if tmp_length != 0:
is_finished = False
if solutionNow[i][j] != 0:
tmp_length += 1
if tmp_length < shortest_item_length:
shortest_item_length = tmp_length
shortest_item_x = i
shortest_item_y = j # print 'shortest item is:',shortest_item_length,shortest_item_x,shortest_item_y
if is_finished:
return False
else:
return {'x': shortest_item_x, 'y': shortest_item_y} def get_next_possible_item(self, solution_array, prev_x, prev_y, solutionNow = None):
if prev_x == -1 and prev_y == -1:
return self.get_first_possible_item(solution_array, solutionNow)
else:
is_finished = True
shortest_item_length = 9
shortest_item_x = 0
shortest_item_y = 0
for tmp_i in range(0, 9, 1):
tmp_length = len(solution_array[tmp_i][prev_y])
if tmp_length != 0:
is_finished = False
if solutionNow[tmp_i][prev_y] != 0:
tmp_length += 1
if tmp_length < shortest_item_length:
shortest_item_length = tmp_length
shortest_item_x = tmp_i
shortest_item_y = prev_y
if tmp_length == 1:
return {'x': shortest_item_x, 'y': shortest_item_y} for tmp_j in range(0, 9, 1):
tmp_length = len(solution_array[prev_x][tmp_j])
if tmp_length != 0:
is_finished = False
if solutionNow[prev_x][tmp_j] != 0:
tmp_length += 1
if tmp_length < shortest_item_length:
shortest_item_length = tmp_length
shortest_item_x = prev_x
shortest_item_y = tmp_j
if tmp_length == 1:
return {'x': shortest_item_x, 'y': shortest_item_y} for x in range(prev_x / 3 * 3, prev_x / 3 * 3 + 3):
for y in range(prev_y / 3 * 3, prev_y / 3 * 3 + 3):
tmp_length = len(solution_array[x][y])
if tmp_length != 0:
is_finished = False
if solutionNow[x][y] != 0:
tmp_length += 1
if tmp_length < shortest_item_length:
shortest_item_length = tmp_length
shortest_item_x = x
shortest_item_y = y
if tmp_length == 1:
return {'x': shortest_item_x, 'y': shortest_item_y}
# print 'shortest item is:',shortest_item_length,shortest_item_x,shortest_item_y
if is_finished:
return self.get_first_possible_item(solution_array,solutionNow)
else:
return {'x': shortest_item_x, 'y': shortest_item_y} problem = \
[
[3,0,8,0,0,0,6,0,0],
[0,4,0,0,6,5,0,0,7],
[7,0,0,4,3,0,0,9,0],
[0,0,7,0,0,1,5,8,0],
[1,0,0,0,2,0,0,0,9],
[0,9,4,7,0,0,2,0,0],
[8,0,0,0,7,4,0,0,0],
[4,0,0,6,5,0,8,1,0],
[0,0,9,0,0,0,7,0,2]
] f = Soduku(problem)
startTime=time.time()
f.resolve()
endTime=time.time()
print "Finished! Time consuming: " + "%.4f" % (endTime-startTime) + " Seconds"

Python解决数独的更多相关文章

  1. 【原创】视频+文字:详解VBA解决数独问题

    [说在前面]: 之前,我在微信朋友圈看到一个同事发了一个状态,说的是她在家辅导孩子做作业,一个数独的题目,好像没有做出来.我看了下,我也做不出来,后来仔细想了下,花了两个多小时时间,用Python编了 ...

  2. POJ2676,HDU4069解决数独的两种实现:DFS、DLX

    搜索实现:解决数独有两种思考策略,一种是枚举当前格能填的数字的种数,这里有一优化策略就是先搜索能填入种数小的格子:另一种是考虑处理某一行(列.宫)时,对于某一个没用过的数字,若该行(列.宫)只有一个可 ...

  3. 《用Python解决数据结构与算法问题》在线阅读

    源于经典 数据结构作为计算机从业人员的必备基础,Java, c 之类的语言有很多这方面的书籍,Python 相对较少, 其中比较著名的一本 problem-solving-with-algorithm ...

  4. 有关科学计算方面的python解决

    在科学计算方面,一般觉得matlab是一个超强的东西.此外还有R. 至于某种语言来说,一般都要讲究一些特别的算法,包含但不限于: 矩阵方面的计算 指数计算 对数计算 多项式运算 各类方程求解 总之.仅 ...

  5. appium+python解决每次运行代码都提示安装Unlock以及AppiumSetting的问题

    appium+python解决每次运行代码都提示安装Unlock以及AppiumSetting的问题(部分安卓机型) 1.修改appium-android-driver\lib下的android-he ...

  6. 高德API+Python解决租房问题(.NET版)

    源码地址:https://github.com/liguobao/58HouseSearch 在线地址:58公寓高德搜房(全国版):http://codelover.link:8080/ 周末闲着无事 ...

  7. python笔记-用python解决小学生数学题【转载】

    本篇转自博客:上海-悠悠 原文地址:http://www.cnblogs.com/yoyoketang/tag/python/ 前几天有人在群里给小编出了个数学题: 假设你有无限数量的邮票,面值分别为 ...

  8. HDU 1426 dancing links解决数独问题

    题目大意: 这是一个最简单的数独填充题目,题目保证只能产生一种数独,所以这里的初始9宫格较为稠密,可以直接dfs也没有问题 但最近练习dancing links,这类数据结构解决数独无疑效率会高很多 ...

  9. 递归回溯生成和解决数独问题c/c++

    数独 程序地址https://github.com/papicheng/blog/tree/master/%E6%95%B0%E7%8B%AC 一.游戏规则介绍: 数独是源自18世纪瑞士的一种数学游戏 ...

随机推荐

  1. fullfile

    这个我总是忽略,见过也不少了,顺便写写,其实一些命令很方便的. 一个例子: root_dir = '../mcg/pre-trained'; addpath(root_dir); addpath(fu ...

  2. WindowsXamlHost:在 WPF 中使用 UWP 的控件(Windows Community Toolkit)

    Windows Community Toolkit 再次更新到 5.0.以前可以在 WPF 中使用有限的 UWP 控件,而现在有了 WindowsXamlHost,则可以使用更多 UWP 原生控件了. ...

  3. SD卡驱动学习

    https://blog.csdn.net/zqixiao_09/article/category/6163492 sd 协议解析: https://blog.csdn.net/g_salamande ...

  4. ballerina 学习二十一 http2

    ballerina 支持http2 协议,包含server push http2 协议 参考代码 import ballerina/http; import ballerina/log;endpoin ...

  5. [CLPR] 用于加速训练神经网络的二阶方法

    本文翻译自: http://www.codeproject.com/Articles/16650/Neural-Network-for-Recognition-of-Handwritten-Digi ...

  6. Phonegap中插件管理

    一.cordova-plugin-console控制台插件的使用 1.进入工程路径后,输入如下命令: cordova plugin add cordova-plugin-console 2. 查看插件 ...

  7. TongWEB与JOnAS 对比,国产中间件战斗机东方通TongWEB源码解析

    转自网址: http://bbs.51cto.com/thread-489819-1-1.html 首先需要声明的是,本人出于技术爱好的角度,以下的文字只是对所看到的一些情况的罗列,偶尔附加个人的一些 ...

  8. SpringCloud初体验:一、Eureka 服务的注册与发现

    Eureka :云端服务发现,一个基于 REST 的服务,用于定位服务,以实现云端中间层服务发现和故障转移. Eureka 可以大致理解为 房产中介 和 房东 的关系,房东想让租客租房子,首先要把房子 ...

  9. Call to your teacher

    链接:https://www.nowcoder.net/acm/contest/76/F来源:牛客网 Call to your teacher 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/ ...

  10. [转]Java IDE 之 IntelliJ IDEA 2017

    参考链接1:http://blog.csdn.net/u012364631/article/details/47682011 IDEA Community(社区版) 使用Maven创建Web工程 并部 ...