根据
9×9盘面上的已知数字,推理出所有剩余空格的数字,并满足每一行、每一列、每一个粗线宫内的数字均含1-9,不重复
python code :
-
# -*- coding:utf-8 -*-
-
-
# temp_list = range(10)
-
# temp_list.pop(0)
-
-
biaozheng=[1,2,3,4,5,6,7,8,9]
-
MAX_LINE=MAX_RAW=9
-
OFFSET = 3
-
-
def check_line(line,count):
-
for i in xrange(MAX_LINE):
-
if shudu[line][i] == count:
-
return False
-
-
return True
-
-
-
def check_raw(raw,count):
-
for i in xrange(MAX_RAW):
-
if shudu[i][raw] == count:
-
return False
-
-
return True
-
-
def check_block(line,raw,count):
-
temp_line = line/OFFSET
-
temp_raw = raw/OFFSET
-
-
for i in xrange(OFFSET):
-
for j in xrange(OFFSET):
-
if shudu[temp_line*3+i][temp_raw*3+j] == count:
-
return False
-
-
return True
-
-
-
def check_all():
-
for i in xrange(MAX_LINE):
-
for j in xrange(MAX_RAW):
-
if shudu[i][j] == 0:
-
return True
-
-
return False
-
-
-
def find_only(temp_x,temp_y):
-
temp_list=[]
-
-
# for i in xrange(MAX_LINE):
-
# temp_list.append(0)
-
-
# print 'init_temp_list= '
-
# for i in xrange(MAX_LINE):
-
# print temp_list[i],
-
-
# for i in xrange(MAX_LINE):
-
# if check_line(temp_x,biaozheng[i]):
-
# if check_raw(temp_y,biaozheng[i]):
-
# if check_block(temp_x,temp_y,biaozheng[i]):
-
# temp_list.append(biaozheng[i])
-
-
for i in xrange(MAX_LINE):
-
if check_line(temp_x,biaozheng[i]) and check_raw(temp_y,biaozheng[i]) and check_block(temp_x,temp_y,biaozheng[i]) :
-
temp_list.append(biaozheng[i])
-
-
if len(temp_list) == 1:
-
# print 'temp_list isnot []'
-
# for j in len(temp_list):
-
# print temp_list[j],
-
return temp_list[0]
-
# else:
-
# print 'temp_list is []'
-
# for i in len(temp_list):
-
# print temp_list[i]
-
-
# print
-
-
# if len(temp_list) == 1:
-
# # for i in len(temp_list):
-
# print temp_list[0]
-
# return temp_list[0]
-
-
-
return 0
-
-
-
if __name__ == '__main__':
-
shudu = []
-
for i in xrange(9):
-
shudu.append([])
-
-
for i in xrange(9):
-
for j in xrange(9):
-
shudu[i].append(0)
-
-
-
shudu[1][2]=shudu[3][0]= shudu[8][7]=shudu[4][8]=shudu[5][4]=1
-
shudu[3][4]=shudu[6][7]=shudu[5][0]=2
-
shudu[0][5]=shudu[2][1]=shudu[4][3]=3
-
shudu[2][3]=shudu[3][8]=shudu[4][0]=shudu[7][2]=4
-
shudu[0][3]=shudu[1][6]=shudu[8][5]=5
-
shudu[0][1]=shudu[5][6]=shudu[6][5]=6
-
shudu[7][8]=shudu[8][3]=7
-
shudu[3][2]=shudu[6][1]=shudu[7][6]=shudu[8][4]=8
-
shudu[0][4]=shudu[1][0]=shudu[2][7]=shudu[4][5]=shudu[5][8]=9
-
-
# for i in xrange(9):
-
# for j in xrange(9):
-
# print shudu[i][j],
-
# print
-
-
-
while check_all():
-
for i in xrange(MAX_LINE):
-
for j in xrange(MAX_RAW):
-
if shudu[i][j]==0 :
-
temp_num = find_only(i,j)
-
if temp_num != 0:
-
shudu[i][j] = temp_num
-
print i,j,temp_num
-
# break
-
-
-
# find_only(0,0)
-
-
-
for i in xrange(9):
-
for j in xrange(9):
-
print shudu[i][j],
-
print
阅读(3821) | 评论(0) | 转发(0) |