python写算法题:leetcode: 36. Valid Sudoku

115 篇文章 0 订阅

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值