大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~
2021_iThome鐵人賽
Leetcode
Determine if a 9 x 9
Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
1-9
without repetition.1-9
without repetition.3 x 3
sub-boxes of the grid must contain the digits 1-9
without repetition.Note:
Input: board =
[["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"]]
Output: true
Input: board =
[["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"]]
Output: false
Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid.
board.length == 9
board[i].length == 9
board[i][j]
is a digit 1-9
or '.'
.首先先簡單的翻譯一下題目給一個數獨題目要你解,給一個數獨題目要判斷這個數獨題目是不是合乎數獨的規則,也就是不管是行、列和9塊3 x 3
的區塊,出現的數字1-9
皆不能重複。
作法大致上是這樣
for rowVal in board:
的方式,只是每個值會在額外配上一個sequence,這個sequence的起始可以透過start
參數來決定。Row
跟Column
來說明。row
和col
這兩個list存著已經出現過的值,假如新讀到的值已經有存在裡頭了,就代表重複了,回傳False
;沒有的話,就存入。subBox
這個list存著已經出現過的值,假如新讀到的值已經有存在裡頭了,就代表重複了,回傳False
;沒有的話,就存入。0,0
、0,1
、0,2
1,0
、1,1
、1,2
2,0
、2,1
、2,2
subBox
的list判斷有沒有重複數字了。class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
row = []
col = []
subBox = []
for seq1, rowVal in enumerate(board, start=0):
for seq2, colVal in enumerate(rowVal, start=0):
if colVal is not ".":
# Row part
if (seq1, colVal) not in row:
row.append((seq1, colVal))
else:
return False
# Column part
if (seq2, colVal) not in col:
col.append((seq2, colVal))
else:
return False
# subBox part
if (int(seq1/3), int(seq2/3), colVal) not in subBox:
subBox.append((int(seq1/3), int(seq2/3), colVal))
else:
return False
return True
Python
大家明天見