问题:给定一个9*9的二维数组,数组元素为1~9的字符串,“,”代表为空,判断其数据的排列是否符合九宫格的规则
示例:
解决思路:分别以行、列、3*3的小九宫格为单位,使用字典对元素进行计数,初始化全部为0;对输入数组的每一个元素进行遍历,“,”跳过,数字字符则判断其在对应行、列、小九宫格中的计数是否为0,不为0则返回False
Python代码:
class Solution(object): def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ row = {i:{str(j):0 for j in range(1,10)} for i in range(9)} col = {i:{str(j):0 for j in range(1,10)} for i in range(9)} part = {m:{j:{str(i):0 for i in range(1,10)} for j in range(3)} for m in range(3)} for i in range(9): for j in range(9): ele = board[i][j] if ele == ".": continue if row[i][ele] or col[j][ele] or part[i//3][j//3][ele]: return False else: row[i][ele] += 1 col[j][ele] += 1 part[i//3][j//3][ele] += 1 return True