判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
数独部分空格内已填入了数字,空白格用 ‘.’ 表示。
示例 1:
输入:
[
[“5”,“3”,".",".",“7”,".",".",".","."],
[“6”,".",".",“1”,“9”,“5”,".",".","."],
[".",“9”,“8”,".",".",".",".",“6”,"."],
[“8”,".",".",".",“6”,".",".",".",“3”],
[“4”,".",".",“8”,".",“3”,".",".",“1”],
[“7”,".",".",".",“2”,".",".",".",“6”],
[".",“6”,".",".",".",".",“2”,“8”,"."],
[".",".",".",“4”,“1”,“9”,".",".",“5”],
[".",".",".",".",“8”,".",".",“7”,“9”]
]
输出: true
示例 2:
输入:
[
[“8”,“3”,".",".",“7”,".",".",".","."],
[“6”,".",".",“1”,“9”,“5”,".",".","."],
[".",“9”,“8”,".",".",".",".",“6”,"."],
[“8”,".",".",".",“6”,".",".",".",“3”],
[“4”,".",".",“8”,".",“3”,".",".",“1”],
[“7”,".",".",".",“2”,".",".",".",“6”],
[".",“6”,".",".",".",".",“2”,“8”,"."],
[".",".",".",“4”,“1”,“9”,".",".",“5”],
[".",".",".",".",“8”,".",".",“7”,“9”]
]
输出: false
解释: 除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。
但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。
说明:
一个有效的数独(部分已被填充)不一定是可解的。
只需要根据以上规则,验证已经填入的数字是否有效即可。
给定数独序列只包含数字 1-9 和字符 '.' 。
给定数独永远是 9x9 形式的。
暴力解决了,排75%
按照规则,首先检查行,再检查列,最后检查9个9宫格
比较复杂的就是检测9个小宫格了,每检测三轮就要初始化行数,因为三行内只有三个九宫格,我用c1来记录轮数,首先检测前三排range(0-3)的三个9宫格,在分别检测range(3-6),range(6,9)的九宫格
for i in board: #检查每一行是否重复
a=[]
for j in i:
if j!='.': #只判断数字
if j in a: #如果重复,则返回False
return False
a.append(j) #不重复,则添加到列表
for i in range(9): #检查每一列是否重复
a=[]
for j in range(9):
if board[j][i]!='.':#只检测数字,空的话就跳过
if board[j][i] in a: #有重复就报错
return False
a.append(board[j][i])
c1=0 # 记录迭代轮数,一共需要迭代24轮(3x8),序号0-8
i1=0#i2,j2表示行,i1,j1表示列
j1=3
i2=0
j2=3
while c1<=24:
a=[] #a=[]一定要迭代满9个数再重置
for i in range(i1,j1): #第一轮:00,10,20,01,11,21,。。。
#range(0,3)检测前三行,range(3-6)检测中间三行
#以此类推
c1=c1+1 #开始迭代,进入c1轮
for j in range(i2,j2): #开始检查range(0-3)列,以此类推
if board[j][i]!='.':
if board[j][i] in a:
return False
a.append(board[j][i])
if c1==3 or c1==6: #迭代其他3x3
i2+=3
j2+=3
elif c1==9 or c1==12 or c1== 15:
i1=3#表示已经检测完毕前三排的三个九宫格,开始检测range(3,6)排
j1=6
if c1==9: #当改变行数时,一定要初始化行,从range(0,3)列开始迭代
i2=-3 #取-3和0是因为下一排要+3
j2=0
i2+=3
j2+=3
elif c1==18 or c1==21 or c1== 24: #重复检测range(6,9)排
i1=6
j1=9
if c1==18:
i2=-3
j2=0
i2+=3
j2+=3
else :
break
return True