https://leetcode.com/problems/valid-sudoku/description/
测试用例少量未通过,分析原因,本程序判断条件更严格,有些明显存在矛盾填写方式,被认定非法数独, 而标准测试用例则认为合法,所以不应该是错误。
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
sodu = {}
judge={}
full=set()
for i in xrange(1, 10):
full.add(i)
for i in xrange(len(board)):
for j in xrange(len(board[i])):
if board[i][j] == '.':
judge[(i,j)]=full.copy()
else:
sodu[(i,j)] = int(board[i][j])
needcheck=1
while len(judge)>0 and needcheck==1:
needcheck=0
for pos in judge.keys():
for i in xrange(3*(pos[0]/3), 3*(pos[0]/3)+3):
for j in xrange(3*(pos[1]/3), 3*(pos[1]/3)+3):
if (i,j) in sodu and sodu[(i,j)] in judge[pos]:
judge[pos].remove(sodu[(i,j)])
for i in xrange(0,9):
if (i,pos[1]) in sodu and sodu[(i,pos[1])] in judge[pos]:
judge[pos].remove(sodu[(i,pos[1])])
if (pos[0], i) in sodu and sodu[(pos[0], i)] in judge[pos]:
judge[pos].remove(sodu[(pos[0], i)])
if len(judge[pos])==0:
return False
if len(judge[pos])==1:
sodu[pos]=list(judge[pos])[0]
del judge[pos]
needcheck = 1
for i in xrange(0,9):
rowset=set()
lineset=set()
blockset=set()
for j in xrange(0,9):
if (i,j) in sodu:
if sodu[(i,j)] in rowset: return False
rowset.add(sodu[(i,j)])
if (j,i) in sodu:
if sodu[(j,i)] in lineset: return False
lineset.add(sodu[(j, i)])
block=(3*(i/3)+j/3, 3*(i%3)+(j%3))
if block in sodu:
if sodu[block] in blockset: return False
blockset.add(sodu[block])
return True