|
| 1 | +# time complexity: O(9!^9) |
| 2 | +# space complexity: O(1) |
| 3 | +from collections import defaultdict |
| 4 | +from typing import List |
| 5 | + |
| 6 | + |
| 7 | +class Solution: |
| 8 | + def solveSudoku(self, board: List[List[str]]) -> None: |
| 9 | + n = len(board) |
| 10 | + |
| 11 | + rows, cols, boxes = defaultdict( |
| 12 | + set), defaultdict(set), defaultdict(set) |
| 13 | + |
| 14 | + for r in range(n): |
| 15 | + for c in range(n): |
| 16 | + if board[r][c] == '.': |
| 17 | + continue |
| 18 | + |
| 19 | + digit = int(board[r][c]) |
| 20 | + rows[r].add(digit) |
| 21 | + cols[c].add(digit) |
| 22 | + boxes[(r // 3) * 3 + c // 3].add(digit) |
| 23 | + |
| 24 | + def isValid(r: int, c: int, digit: int): |
| 25 | + boxId = (r // 3) * 3 + c // 3 |
| 26 | + return digit not in rows[r] and digit not in cols[c] and digit not in boxes[boxId] |
| 27 | + |
| 28 | + def backtrack(r: int, c: int): |
| 29 | + if r == n - 1 and c == n: |
| 30 | + return True |
| 31 | + elif c == n: |
| 32 | + c = 0 |
| 33 | + r += 1 |
| 34 | + |
| 35 | + if board[r][c] != '.': |
| 36 | + return backtrack(r, c + 1) |
| 37 | + |
| 38 | + boxId = (r // 3) * 3 + c // 3 |
| 39 | + for digit in range(1, n + 1): |
| 40 | + if not isValid(r, c, digit): |
| 41 | + continue |
| 42 | + |
| 43 | + board[r][c] = str(digit) |
| 44 | + rows[r].add(digit) |
| 45 | + cols[c].add(digit) |
| 46 | + boxes[boxId].add(digit) |
| 47 | + |
| 48 | + if backtrack(r, c + 1): |
| 49 | + return True |
| 50 | + |
| 51 | + board[r][c] = '.' |
| 52 | + rows[r].remove(digit) |
| 53 | + cols[c].remove(digit) |
| 54 | + boxes[boxId].remove(digit) |
| 55 | + |
| 56 | + return False |
| 57 | + |
| 58 | + backtrack(0, 0) |
| 59 | + |
| 60 | + |
| 61 | +board = [ |
| 62 | + ["5", "3", ".", ".", "7", ".", ".", ".", "."], |
| 63 | + ["6", ".", ".", "1", "9", "5", ".", ".", "."], |
| 64 | + [".", "9", "8", ".", ".", ".", ".", "6", "."], |
| 65 | + ["8", ".", ".", ".", "6", ".", ".", ".", "3"], |
| 66 | + ["4", ".", ".", "8", ".", "3", ".", ".", "1"], |
| 67 | + ["7", ".", ".", ".", "2", ".", ".", ".", "6"], |
| 68 | + [".", "6", ".", ".", ".", ".", "2", "8", "."], |
| 69 | + [".", ".", ".", "4", "1", "9", ".", ".", "5"], |
| 70 | + [".", ".", ".", ".", "8", ".", ".", "7", "9"] |
| 71 | +] |
| 72 | +print(Solution().solveSudoku(board)) |
0 commit comments