输入文件格式:
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=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+1 18 column=c.column 19 return cellArray[row][column] 20 elif c.column+1<columnMax: 21 row=0 22 column=c.column+1 23 return cellArray[row][column] 24 else: 25 return None 26 27 class Cell: 28 def __init__(self,row,column): 29 self.row=row 30 self.column=column 31 self.value=0 32 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 True 38 if cell.value==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 False 45 for canNum in canList: 46 cell.value=canNum 47 res=setCellValue(mynext(cell)) 48 if res: 49 return True 50 cell.value=0 51 return False 52 else: 53 return setCellValue(mynext(cell)) 54 def blockCheck(canList,cell): 55 blockrow=cell.row/3 56 blockcolumn=cell.column/3 57 for i in range(blockrow*3,(blockrow+1)*3): 58 for j in range(blockcolumn*3,(blockcolumn+1)*3): 59 cvalue=cellArray[i][j].value 60 if cellArray[i][j].value==0: 61 continue 62 if cvalue in canList: 63 canList.remove(cvalue) 64 65 def rowCheck(canList,cell): 66 for i in range(columnMax): 67 cvalue=cellArray[cell.row][i].value 68 if cvalue==0: 69 continue 70 if cvalue in canList: 71 canList.remove(cvalue) 72 73 def columnCheck(canList,cell): 74 for i in range(rowMax): 75 cvalue=cellArray[i][cell.column].value 76 if cvalue==0: 77 continue 78 if cvalue in canList: 79 canList.remove(cvalue) 80 81 print ‘yuan‘ 82 print ‘*‘*20 83 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 ‘*‘*20 90 print ‘result‘ 91 print ‘*‘*20 92 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"