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. Opencv中Rect类

    转载: Rect_类有些意思,成员变量x.y.width.height,分别为左上角点的坐标和矩形的宽和高.常用的成员函数有Size()返回值为一个Size,area()返回矩形的面积,contain ...

  2. CMS初步认识

    一CMS本质 [1]基本思想是:分离内容的管理和设计,页面显示的风格和框架存储在模板里.至于页面显示的内容存储在数据库中或一个独立的文件中.当一个用户请求页面时,各部分联合生成一个标准的 HTML 页 ...

  3. Request.getInputStrema只能读取一次的分析过程

    1. 我们先来看一下继承关系HttpServletRequest 接口继承ServletRequest接口 public abstract interface  ServletRequest{ pub ...

  4. MacOS 如何截屏

    在Mac OS X下有很强大的截屏功能,它不仅仅是对屏幕的全屏COPY,而是包括很多细节在里面,就从这点来看,已经比过所有版本的Windows了. 下面我来向大家详细介绍一下: 对全屏的截图我们可以通 ...

  5. sourcegraph 方便的代码查看工具

    sourcegraph 是一个方便的代码查看插件,有chrome 的插件,具体安装可以在chrome 应用商店,同时 官方提供了基于docker 运行的方式(适合本地使用) 下载镜像 docker p ...

  6. c/c++指针详解(一)

    一:相关概念 1.指针数组:int *p[6]               是数组,是一个存放指针的数组,也就是里面存放的是地址. 2.数组指针:int (*p)[6]                 ...

  7. dell R730 安装windwos 2008 R2在windows loading files...完成后屏幕无信号(iDrac绿屏)

    dell R730 安装windwos 2008 R2在windows loading files...完成后,Starting Windows时屏幕无信号(iDrac绿屏) 解决方法: F2  进行 ...

  8. Window平台下React Native 开发环境搭建

    1. 安装Node.js 2. 安装react-native-cli 命令行工具 npm install -g react-nativew-cli 3. 创建项目 $ react-native ini ...

  9. WPF学习基础

    1. d:DesignHeight="300" d:DesignWidth="200": 分别指的是在vs设计界面的宽高,Width="500&quo ...

  10. Unable to locate \.nuget\NuGet.exe 问题解决办法之一

    问题出现的原因是项目下.nuget文件夹下NuGet.exe文件夹不存在导致的 解决办法: 1.右键编辑NuGet.targets文件 将下载NuGet.exe的配置节点DownloadNuGetEx ...