判斷乙個 9x9 的數獨是否有效。只需要根據以下規則,驗證已經填入的數字是否有效即可。
數字1-9
在每一行只能出現一次。
數字1-9
在每一列只能出現一次。
數字1-9
在每乙個以粗實線分隔的3x3
宮內只能出現一次。
上圖是乙個部分填充的有效的數獨。
數獨部分空格內已填入了數字,空白格用'.'
表示。
示例 1:
輸入:[示例 2:["5","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]輸出:true
輸入:[說明:思路:["8","3",".",".","7",".",".",".","."],
["6",".",".","1","9","5",".",".","."],
[".","9","8",".",".",".",".","6","."],
["8",".",".",".","6",".",".",".","3"],
["4",".",".","8",".","3",".",".","1"],
["7",".",".",".","2",".",".",".","6"],
[".","6",".",".",".",".","2","8","."],
[".",".",".","4","1","9",".",".","5"],
[".",".",".",".","8",".",".","7","9"]
]輸出:false解釋:除了第一行的第乙個數字從5改為8以外,空格內其他數字均與 示例1 相同。
但由於位於左上角的 3x3 宮內有兩個 8 存在, 因此這個數獨是無效的。
數獨有效必須滿足三個條件:
1. 每一行1-9
2. 每一列1-9
3. 每個3*3的方塊1-9
所以可以用三個字典來記錄行、列和方塊的已有元素情況。比如
row[1] = [1, 3, 5]就代表第一行已經出現了1, 3和5,如果下乙個3又出現在了第一行,就說明數獨無效。
class solution(object):
def isvalidsudoku(self, board):
""":type board: list[list[str]]
:rtype: bool
"""from collections import defaultdict
row, column, squre = defaultdict(set), defaultdict(set), defaultdict(set)
for i in range(9):
for j in range(9):
if board[i][j].isdigit(): #排除掉空的情況
if board[i][j] in row[i] or board[i][j] in column[j] or (board[i][j]) in squre[(i // 3, j // 3)]:
return false
else:
row[i].add(board[i][j])
column[j].add(board[i][j])
squre[(i // 3, j // 3)].add(board[i][j])
return true
leetcode python3 整數轉羅馬數字
1.思路 將數字分解成千位數 百位數 個位數,對不同的位數中分3個階段進行討論 9的 5 8之間的 4的 1 3之間的。對於不同的分位數和階段加上不同的符號處理 2.class solution def inttoroman self,num str if int num 1000 0 for i ...
leetcode python3演算法 島嶼個數
1.題目描述 給定乙個由 1 陸地 和 0 水 組成的的二維網格,計算島嶼的數量。乙個島被水包圍,並且它是通過水平方向或垂直方向上相鄰的陸地連線而成的。你可以假設網格的四個邊均被水包圍。示例 1 輸入 11110 11010 11000 00000 輸出 1 示例 2 輸入 11000 11000 ...
單排leetcode python3 兩數相加
給定兩個非空鍊錶來代表兩個非負數,位數按照逆序方式儲存,它們的每個節點只儲存單個數字。將這兩數相加會返回乙個新的鍊錶。你可以假設除了數字 0 之外,這兩個數字都不會以零開頭。示例 輸入 2 4 3 5 6 4 輸出 7 0 8原因 342 465 807class listnode def init...