Grokking the Coding Interview: Patterns for Coding Questions
Vote
0% completed
Sudoku Solver (hard)
Problem Statement
Write a program to solve a Sudoku puzzle by filling the empty cells.
A sudoku solution must satisfy all of the following rules:
- Each of the digits 1-9 must occur exactly once in each row.
- Each of the digits 1-9 must occur exactly once in each column.
- Each of the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid.
The '.' character indicates empty cells.
Example 1:
Input:
{'5', '3', '.', '.', '7', '.', '.', '.', '.'},
{'6', '.', '.', '1', '9', '5', '.', '.', '.'},
{'.', '9', '8', '.', '
.....
.....
.....
Like the course? Get enrolled and start learning!
Mohammed Dh Abbas
· 2 years ago
class Solution: def __init__(self): self.rows = {i: set() for i in range(9)} self.cols = {i: set() for i in range(9)} self.boxes = {i: set() for i in range(9)} def get_box_number(self, row, col): return (row // 3) * 3 + (col // 3) def init_used_numbers(self, board): for i in range(9): for j in range(9): if board[i][j] != '.': num = int(board[i][j]) self.rows[i].add(num) self.cols[j].add(num) self.boxes[self.get_box_number(i, j)].add(num) def is_valid(self, row, col, num): box_num = self.get_box_number(row, col) return num not in self.rows[row] and num not in self.cols[col] and num not in self.box