|
| 1 | +class Solution(object): |
| 2 | + def solveSudoku(self, board): |
| 3 | + """ |
| 4 | + :type board: List[List[str]] |
| 5 | + :rtype: None Do not return anything, modify board in-place instead. |
| 6 | + """ |
| 7 | + # Helper functions for bit manipulation |
| 8 | + def char_to_index(ch): |
| 9 | + return ord(ch) - ord('1') |
| 10 | + |
| 11 | + def index_to_char(index): |
| 12 | + return chr(index + ord('1')) |
| 13 | + |
| 14 | + # Initialize bitmasks for rows, columns, and boxes |
| 15 | + rows = [0] * 9 |
| 16 | + cols = [0] * 9 |
| 17 | + boxes = [0] * 9 |
| 18 | + |
| 19 | + # Populate bitmasks with initial board values |
| 20 | + for r in range(9): |
| 21 | + for c in range(9): |
| 22 | + if board[r][c] != '.': |
| 23 | + num = char_to_index(board[r][c]) |
| 24 | + bit = 1 << num |
| 25 | + rows[r] |= bit |
| 26 | + cols[c] |= bit |
| 27 | + boxes[(r // 3) * 3 + (c // 3)] |= bit |
| 28 | + |
| 29 | + # Check if placing a number is valid |
| 30 | + def is_valid(row, col, num): |
| 31 | + bit = 1 << num |
| 32 | + box_index = (row // 3) * 3 + (col // 3) |
| 33 | + return not (rows[row] & bit or cols[col] & bit or boxes[box_index] & bit) |
| 34 | + |
| 35 | + # Forward Checking to find the most constrained cell |
| 36 | + def select_cell(): |
| 37 | + min_possibilities = float('inf') |
| 38 | + cell = None |
| 39 | + for row in range(9): |
| 40 | + for col in range(9): |
| 41 | + if board[row][col] == '.': |
| 42 | + possibilities = 0 |
| 43 | + for num in range(9): |
| 44 | + if is_valid(row, col, num): |
| 45 | + possibilities += 1 |
| 46 | + if possibilities < min_possibilities: |
| 47 | + min_possibilities = possibilities |
| 48 | + cell = (row, col) |
| 49 | + return cell |
| 50 | + |
| 51 | + # Recursive function to solve the board |
| 52 | + def solve(): |
| 53 | + cell = select_cell() |
| 54 | + if cell is None: |
| 55 | + return True # All cells are filled |
| 56 | + |
| 57 | + row, col = cell |
| 58 | + for num in range(9): |
| 59 | + if is_valid(row, col, num): |
| 60 | + bit = 1 << num |
| 61 | + board[row][col] = index_to_char(num) |
| 62 | + rows[row] |= bit |
| 63 | + cols[col] |= bit |
| 64 | + boxes[(row // 3) * 3 + (col // 3)] |= bit |
| 65 | + |
| 66 | + if solve(): |
| 67 | + return True |
| 68 | + |
| 69 | + board[row][col] = '.' |
| 70 | + rows[row] &= ~bit |
| 71 | + cols[col] &= ~bit |
| 72 | + boxes[(row // 3) * 3 + (col // 3)] &= ~bit |
| 73 | + |
| 74 | + return False |
| 75 | + |
| 76 | + solve() |
0 commit comments