36. Valid Sudoku
1. Description
- Determine if aย
9 x 9ย Sudoku boardย is valid.ย Only the filled cells need to be validatedย according to the following rules:
- Each rowย must contain theย digitsย
1-9ย without repetition. - Each column must contain the digitsย
1-9ย without repetition. - Each of the nineย
3 x 3ย sub-boxes of the grid must contain the digitsย1-9ย without repetition.
Note:
- A Sudoku board (partially filled) could be valid but is not necessarily solvable.
- Only the filled cells need to be validated according to the mentionedย rules.
2. Example
Example 1
**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
Example 2
**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.
3. Solution
- Runtime: 0ms
- ์ค๋ช
- ์ด ๋ฌธ์ ๋ ๋ด๊ฐ ๋ฅผ ๋๋ฌด ์๊ฐํด์
for๋ฌธ์ ๋๋ฒ ๋๋ฆฌ๋๊ฑธ ์๊ฐ์ ์ํ๊ณ ํ๋ ค๊ณ ํ๋๋ ๋ชปํ์๋ค. - ๋ต์ง๋ฅผ ๋ณด๊ณ ์ดํดํ๋ฉฐ Chat GPT๋ฅผ ๋ณด๊ณ ์ฝ๋ ๋ถ์์ ์งํํ๋ค.
- ํ(row), ์ด(column), ๋ฐ์ค(box)๋ฅผ ์ ์ฅํ ์๋ฃ๊ตฌ์กฐ ์์ฑํ๋ค.
- ์ค๋์ฟ ๋ณด๋์
.(๋น ์นธ)์ด๋ฉด ๊ฑด๋๋ด๋ค. if board[r][c] in rows[r] or board[r][c] in cols[c] or board[r][c] in boxes[(r //3, c//3)]:- ์ซ์๊ฐ ์ค๋ณต๋๋์ง ๊ฒ์ฌํ๋ค.
- ์ค๋ณต์ด ์๋๋ผ๋ฉด ์ซ์๋ฅผ ์ ์ฅํ๋ค.
- ์ด ๋ฌธ์ ๋ ๋ด๊ฐ ๋ฅผ ๋๋ฌด ์๊ฐํด์
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = defaultdict(set)
cols = defaultdict(set)
boxes = defaultdict(set)
for r in range(9):
for c in range(9):
if board[r][c] == ".":
continue
if board[r][c] in rows[r] or board[r][c] in cols[c] or board[r][c] in boxes[(r //3, c//3)]:
return False
rows[r].add(board[r][c])
cols[c].add(board[r][c])
boxes[(r // 3, c // 3)].add(board[r][c])
return True- ๐
defaultdict๋?- ๋ชจ๋ Key์ ๋ํด ๊ธฐ๋ณธ(default) ๊ฐ์ ์ค์ ํด์ค๋ค.
defaultdict(set)์ด๋ฉด- ๋์
๋๋ฆฌ Key๊ฐ์
set์ default ๊ฐ์ผ๋ก ์ง์ ํ๋ค๋ ๊ฒ์ด๋ค.
- ๋์
๋๋ฆฌ Key๊ฐ์
- โ๏ธ๋ด๊ฐ ์ดํดํ์ง ๋ชปํ๋ ๋ถ๋ถ
- ์ซ์ ์ ์ฅ์ด ํ์ํ ์ด์
- ์ค๋ณต๋๋ ์ซ์๊ฐ ์์ด์ผ ํ๊ธฐ ๋๋ฌธ์ ์ด๋ฏธ ๋ฑ์ฅํ ์ซ์๋ฅผ ์ ์ฅํ์ฌ ์ค๋ณต์ด ๋ฐ์ํ๋์ง ๋น ๋ฅด๊ฒ ํ์ธํ๊ธฐ ์ํด
set๋ฅผ ์ฌ์ฉํ์ฌ ํ์ธํ๋ค.
- ์ค๋ณต๋๋ ์ซ์๊ฐ ์์ด์ผ ํ๊ธฐ ๋๋ฌธ์ ์ด๋ฏธ ๋ฑ์ฅํ ์ซ์๋ฅผ ์ ์ฅํ์ฌ ์ค๋ณต์ด ๋ฐ์ํ๋์ง ๋น ๋ฅด๊ฒ ํ์ธํ๊ธฐ ์ํด
- ์ซ์ ์ ์ฅ์ด ํ์ํ ์ด์
4. What I Learned
References
