赞
踩
一个简单的方法是,遍历9*9
书读三次,以确保:
3*3
子数独中没有重复的数字box_index = (row/3*3 + columns / 3
,其中/
是整出value -> count
哈希映射来跟踪所有已经遇到的值class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: # init data rows = [{} for i in range(9)] columns = [{} for i in range(9)] boxes = [{} for i in range(9)] # validate a board for i in range(9): for j in range(9): num = board[i][j] if num != '.': num = int(num) box_index = (i // 3 ) * 3 + j // 3 # keep the current cell value rows[i][num] = rows[i].get(num, 0) + 1 columns[j][num] = columns[j].get(num, 0) + 1 boxes[box_index][num] = boxes[box_index].get(num, 0) + 1 # check if this value has been already seen before if rows[i][num] > 1 or columns[j][num] > 1 or boxes[box_index][num] > 1: return False return True
时间复杂度:
O
(
N
)
O(N)
O(N)
空间复杂度:
O
(
1
)
O(1)
O(1)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。