【LeetCode】36. 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 '.'.

A partially filled sudoku which is valid.

题意:判断数独表中的数字是否违反规则

遍历表,每遍历到一个位置,判断此位置中的数字在对应的行 ,列,单元集合中是否已经存在,已经存在的话返回False

 1 class Solution(object):
 2     def isValidSudoku(self, board):
 3         """
 4         :type board: List[List[str]]
 5         :rtype: bool
 6         """
 7         flag = [set() for i in range(27)]
 8         for i in range(9):
 9             for j in range(9):
10                 if board[i][j] != '.':
11                     if board[i][j] not in flag[i]:
12                         flag[i].add(board[i][j])
13                     else: return False
14                     
15                     if board[i][j] not in flag[j+9]:
16                         flag[j+9].add(board[i][j])
17                     else: return False
18                     
19                     r = i/3
20                     c = j/3
21                     n = r*3+c
22                     if board[i][j] not in flag[n+18]:
23                         flag[n+18].add(board[i][j])
24                     else: return False
25                     
26                 else: pass
27         return True
原文地址:https://www.cnblogs.com/fcyworld/p/6285604.html