天天看點

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(,)]
        row_flag = dict.fromkeys(s,False)
        col_flag = dict.fromkeys(s,False)
        flag = dict.fromkeys(s,False)

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

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

                    for m in range(i-,i+):
                        for n in range(j-,j+):
                            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(,):
        for j in range(,):
            print a[i][j],' ',
        print