Python解决数独
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解决数独的更多相关文章
- 【原创】视频+文字:详解VBA解决数独问题
[说在前面]: 之前,我在微信朋友圈看到一个同事发了一个状态,说的是她在家辅导孩子做作业,一个数独的题目,好像没有做出来.我看了下,我也做不出来,后来仔细想了下,花了两个多小时时间,用Python编了 ...
- POJ2676,HDU4069解决数独的两种实现:DFS、DLX
搜索实现:解决数独有两种思考策略,一种是枚举当前格能填的数字的种数,这里有一优化策略就是先搜索能填入种数小的格子:另一种是考虑处理某一行(列.宫)时,对于某一个没用过的数字,若该行(列.宫)只有一个可 ...
- 《用Python解决数据结构与算法问题》在线阅读
源于经典 数据结构作为计算机从业人员的必备基础,Java, c 之类的语言有很多这方面的书籍,Python 相对较少, 其中比较著名的一本 problem-solving-with-algorithm ...
- 有关科学计算方面的python解决
在科学计算方面,一般觉得matlab是一个超强的东西.此外还有R. 至于某种语言来说,一般都要讲究一些特别的算法,包含但不限于: 矩阵方面的计算 指数计算 对数计算 多项式运算 各类方程求解 总之.仅 ...
- appium+python解决每次运行代码都提示安装Unlock以及AppiumSetting的问题
appium+python解决每次运行代码都提示安装Unlock以及AppiumSetting的问题(部分安卓机型) 1.修改appium-android-driver\lib下的android-he ...
- 高德API+Python解决租房问题(.NET版)
源码地址:https://github.com/liguobao/58HouseSearch 在线地址:58公寓高德搜房(全国版):http://codelover.link:8080/ 周末闲着无事 ...
- python笔记-用python解决小学生数学题【转载】
本篇转自博客:上海-悠悠 原文地址:http://www.cnblogs.com/yoyoketang/tag/python/ 前几天有人在群里给小编出了个数学题: 假设你有无限数量的邮票,面值分别为 ...
- HDU 1426 dancing links解决数独问题
题目大意: 这是一个最简单的数独填充题目,题目保证只能产生一种数独,所以这里的初始9宫格较为稠密,可以直接dfs也没有问题 但最近练习dancing links,这类数据结构解决数独无疑效率会高很多 ...
- 递归回溯生成和解决数独问题c/c++
数独 程序地址https://github.com/papicheng/blog/tree/master/%E6%95%B0%E7%8B%AC 一.游戏规则介绍: 数独是源自18世纪瑞士的一种数学游戏 ...
随机推荐
- pyalgotrade入门
入门代码解析: from pyalgotrade import strategyfrom pyalgotrade.barfeed import yahoofeed #继承自BacktestingStr ...
- TypeScript学习笔记(二) - 基本类型
本篇将简单介绍TypeScript的几种基本类型. TypeScript基本类型有如下几种: Boolean Number String Array Tuple Enum Any 另外还有void类型 ...
- 10件在PHP7中不要做的事情
10件在PHP7中不要做的事情 1. 不要使用mysql_函数 这一天终于来了,从此你不仅仅“不应该”使用mysql_函数.PHP 7 已经把它们从核心中全部移除了,也就是说你需要迁移到好得多的mys ...
- JSP动作指令
JSP动作指令 动作指令与编译指令不间,编译指令是通知 Servlet 引擎的处理消息,而动作指令只是运行时的脚本动作.编译指令在将JSP 编译成 Servlet 时起作用:处理指令通常可替换成 Ja ...
- CentOS7 防火墙配置-详解
CentOS 7 防火墙配置 1.防火墙的简述 防火墙对服务器起到一定的保护作用,所以了解一些相关的操作是很有必要的. 在CentOS 7.x中,有了一种新的防火墙策略叫FireWall , 在6.x ...
- 在 Linux redis 验证交互连接过程中遇到 redis Could not connect to Redis at 127.0.0.1:6379: Connection refused 的解决方法
Could not connect to Redis at 127.0.0.1:6379: Connection refused 1.找到redis.conf 并修改 daemonize no 为 d ...
- oracle/ms sql 系统表
sql server系统表详细说明 sysaltfiles 主数据库 保存数据库的文件 syscharsets 主数据库字符集与排序顺序 sysconfigures主数据库 配置选项 syscurco ...
- Data_Structure04-树
一.学习总结 1.树结构思维导图 2.树结构学习体会 树结构,从字面上的意思来看,可以简单的理解为数据像一棵树一样展开存储.在学习本章的内容中,一开始只是理解了概念,在真正做题中,一点思路都没有,不知 ...
- Linux虚拟机与Windows共享文件
1.找到“虚拟机” >>> “设置” 2.选项 >>> 共享文件夹 >>> 总是启用 >>> 添加,选择你想要共享的文件. 注 ...
- 1021 docker搭建mysql、网络模式、grid
1.搭建并连接mysql服务 1.1.mysql官方命令 https://hub.docker.com/_/mysql/ #下载mysql镜像: docker pull mysql #启动mysql: ...