Python生成数独地图的一种简易方法
python代码块
# -*- coding: utf-8 -*-
"""
Created on Sat May 15 18:29:32 2021
@author: Administrator
"""
import random
mmap=[[0 for i in range(9)]for j in range(9)]
#生成数独的一行,即9个值为1-9的数
def randline(x):
l=list(range(1,10))
for i in range(len(x)):
x[i]=l[random.randint(0,len(l)-1)]
l.remove(x[i])
return x
#判断纵向是否冲突
def zx_conflict(row):
for i in range(row):
for j in range(9):
if mmap[row][j]==mmap[i][j]:
return 1
return 0
#判断九宫格是否冲突
def jgg_conflict(row):
m=[[0,1,2],[3,4,5],[6,7,8]]
index=0
for i in range(len(m)):
if row in m[i]:
index=i
comp=list()
for i in m:
comp.append([])
for j in m[index]:
comp[-1].append(mmap[j][i[0]])
comp[-1].append(mmap[j][i[1]])
comp[-1].append(mmap[j][i[2]])
for i in range(3):
comp[i].remove(mmap[row][0+3*i])
comp[i].remove(mmap[row][1+3*i])
comp[i].remove(mmap[row][2+3*i])
for i in range(9):
if mmap[row][i] in comp[i//3]:
return 1
return 0
#for item in range(1000):
randline(mmap[0])
for i in range(1,9):
it=0
flag=0
randline(mmap[i])
while zx_conflict(i) or jgg_conflict(i):
randline(mmap[i])
it+=1
if it>1000000: #100万次随机生成基本能确保生成一行满足列、九宫格限制的数独值
flag=1
break
print(it) #打印生成每一行数独需要的随机次数
if flag==1:
# print(1)
break
if i==8:
print("success")
else:
print("default")
效果图片: