难度:中等
判断一个 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 形式的。
思路:这个地方我没什么好的思路,直接采取遍历的方式,有两种想法,第一种是申请27个数组,9个用来存入行判断,9个判断列,9个判断3*3;只需要遍历即可,每个数据都存入对于的数组内(一个数要存3个数组)然后中间判断是否存在即可;第二种方法是,只申请一个数组,遍历三遍,行、列、3*3各一次,每次用一个数组判断就可以。
代码如下(3次循环,时间复杂度打败60%+,空间仅打败6%+):
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
l=len(board)
#要么遍历一次,申请3*l个数组来判断,也可以遍历三次,只需要一个数组即可
list1=[]
flag=0
#行判断
for i in range(l):
list1=[]
for j in range(l):
if board[i][j] not in list1 and board[i][j]!=".":
list1.append(board[i][j])
elif board[i][j] in list1:
flag=1
break
#不符合行则直接结束
if flag==1:
return False
#列判断
for i in range(l):
list1=[]
for j in range(l):
if board[j][i] not in list1 and board[j][i]!=".":
list1.append(board[j][i])
elif board[j][i] in list1:
flag=1
break
#不符合列则直接结束
if flag==1:
return False
#九宫格判断
#将9*9分解为9个3*3,坐标分别为(0,1,2)*(0,1,2)
for i in range(l/3):
for j in range(l/3):
list1=[]
#print(j)
#现在遍历3*3
for k in range(l/3):
for m in range(l/3):
#这里改了改判断方式,其实都一样的效果
if board[i*3+k][j*3+m]!=".":
if board[i*3+k][j*3+m] not in list1 :
list1.append(board[i*3+k][j*3+m])
else:
flag=1
break
if flag==1:
return False
else:
return True