36 leetcode - Valid Sudoku

来源:互联网 发布:清弓的老贾有淘宝店吗? 编辑:程序博客网 时间:2024/06/05 10:48
#!/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 Trueif __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
0 0
原创粉丝点击