因爲工做緣由,之後A題通常都使用Python,不得不說Python還挺方便的,做爲一個腳本語言學好了,會省不少事情。this
判斷一個 9x9 的數獨是否有效。只須要根據如下規則,驗證已經填入的數字是否有效便可。spa
1-9
在每一行只能出現一次。1-9
在每一列只能出現一次。1-9
在每個以粗實線分隔的 3x3
宮內只能出現一次。Code 1:code
class Solution: def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ for i in range(9): for j in range(9): if board[i][j] == '.': board[i][j] = 0 else : board[i][j] = int(board[i][j]) flag = [0] * 10 ans = True for i in range(9): flag = [0] * 10 for j in range(9): if board[i][j] == 0: continue flag[board[i][j]]+=1 if flag[board[i][j]] > 1: ans = False flag = [0] * 10 for j in range(9): flag = [0] * 10 for i in range(9): if board[i][j] == 0: continue flag[board[i][j]] +=1 if flag[board[i][j]] > 1: ans = False for i in range(0,9,3): for j in range(0,9,3): flag = [0]*10 for m in range(3): for n in range(3): if board[i+m][j+n] == 0: continue flag[board[i+m][j+n]] +=1 if flag[board[i+m][j+n]] > 1: ans = False return ans
Code : 2blog
class Solution: def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: 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 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