36 leetcode - Valid Sudoku

#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Valid Sudoku.
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'.
检查填了数字的部分符合数独的规则即可.
1.每一行都必须在1-9的范围内,且只出现一次。
2.每一列都必须在1-9的范围内,且只出现一次。
3.数字1-9在每个子宫格中只出现一次。
'''
class Solution(object):
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
        if not board:
            return False

        s = [str(i) for i in range(1,10)]
        row_flag = dict.fromkeys(s,False)
        col_flag = dict.fromkeys(s,False)
        flag = dict.fromkeys(s,False)

        for i in xrange(0,9):
            for k in s:
                row_flag[k] = False
                col_flag[k] = False

            for j in xrange(0,9):
                if (i + 1) % 3 == 0 and (j + 1) % 3 == 0:
                    for k in s:
                        flag[k] = False

                    for m in range(i-2,i+1):
                        for n in range(j-2,j+1):
                            if board[m][n] != '.':
                                if flag[board[m][n]] == True:
                                    return False
                                flag[board[m][n]] = True

                if board[i][j] != '.':
                    if row_flag[board[i][j]] == True:
                        return False
                    row_flag[board[i][j]] = True

                if board[j][i] != '.':
                    if col_flag[board[j][i]] == True:
                        return False
                    col_flag[board[j][i]] = True
        return True




if __name__ == "__main__":
    s = Solution()
    print s.isValidSudoku(["..5.....6","....14...",".........",".....92..","5....2...",".......3.","...54....","3.....42.","...27.6.."])
    a = ["..4...63.",".........","5......9.","...56....","4.3.....1","...7.....","...5.....",".........","........."]
    for i in range(0,9):
        for j in range(0,9):
            print a[i][j],' ',
        print
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值