首页 > 代码库 > python 实现计算数独
python 实现计算数独
输入文件格式:
008309100
900060004
007504800
036000540
001000600
042000970
005907300
600010008
004608200
输出结果:
yuan
********************
0 0 8 3 0 9 1 0 0
9 0 0 0 6 0 0 0 4
0 0 7 5 0 4 8 0 0
0 3 6 0 0 0 5 4 0
0 0 1 0 0 0 6 0 0
0 4 2 0 0 0 9 7 0
0 0 5 9 0 7 3 0 0
6 0 0 0 1 0 0 0 8
0 0 4 6 0 8 2 0 0
********************
result
********************
4 2 8 3 7 9 1 6 5
9 5 3 8 6 1 7 2 4
1 6 7 5 2 4 8 3 9
8 3 6 7 9 2 5 4 1
7 9 1 4 3 5 6 8 2
5 4 2 1 8 6 9 7 3
2 8 5 9 4 7 3 1 6
6 7 9 2 1 3 4 5 8
3 1 4 6 5 8 2 9 7
1 cellArray=[] 2 rowMax=9 3 columnMax=9 4 def pre(): 5 with open(r"C:\Python27\sd.txt") as infile: 6 l=[s for s in infile] 7 for i in range(rowMax): 8 rowArray=[] 9 for j in range(columnMax):10 c=Cell(i,j)11 c.value=http://www.mamicode.com/int(l[i][j])12 rowArray.append(c)13 cellArray.append(rowArray)14 15 def mynext(c):16 if c.row+1<rowMax:17 row=c.row+118 column=c.column19 return cellArray[row][column]20 elif c.column+1<columnMax:21 row=022 column=c.column+123 return cellArray[row][column]24 else:25 return None26 27 class Cell:28 def __init__(self,row,column):29 self.row=row30 self.column=column31 self.value=http://www.mamicode.com/032 def __str__(self):33 return str(self.row)+":"+str(self.column)+":"+str(self.value)34 35 def setCellValue(cell):36 if cell==None:37 return True38 if cell.value=http://www.mamicode.com/=0:39 canList=[1,2,3,4,5,6,7,8,9]40 blockCheck(canList,cell)41 rowCheck(canList,cell)42 columnCheck(canList,cell)43 if len(canList) ==0:44 return False45 for canNum in canList:46 cell.value=http://www.mamicode.com/canNum47 res=setCellValue(mynext(cell))48 if res:49 return True50 cell.value=http://www.mamicode.com/051 return False52 else:53 return setCellValue(mynext(cell))54 def blockCheck(canList,cell):55 blockrow=cell.row/356 blockcolumn=cell.column/357 for i in range(blockrow*3,(blockrow+1)*3):58 for j in range(blockcolumn*3,(blockcolumn+1)*3):59 cvalue=http://www.mamicode.com/cellArray[i][j].value60 if cellArray[i][j].value=http://www.mamicode.com/=0:61 continue62 if cvalue in canList:63 canList.remove(cvalue)64 65 def rowCheck(canList,cell):66 for i in range(columnMax):67 cvalue=http://www.mamicode.com/cellArray[cell.row][i].value68 if cvalue=http://www.mamicode.com/=0:69 continue70 if cvalue in canList:71 canList.remove(cvalue)72 73 def columnCheck(canList,cell):74 for i in range(rowMax):75 cvalue=http://www.mamicode.com/cellArray[i][cell.column].value76 if cvalue=http://www.mamicode.com/=0:77 continue78 if cvalue in canList:79 canList.remove(cvalue)80 81 print ‘yuan‘82 print ‘*‘*2083 pre()84 for i in range(rowMax):85 for j in range(columnMax):86 print str(cellArray[i][j].value),87 print "\n"88 89 print ‘*‘*2090 print ‘result‘91 print ‘*‘*2092 setCellValue(cellArray[0][0])93 for i in range(rowMax):94 for j in range(columnMax):95 print str(cellArray[i][j].value),96 print "\n"
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。