Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
LeetCode/sudoku-solver
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
76 lines (62 sloc)
2.33 KB
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 the digits 1-9 must occur exactly once in each of the 9 3x3 sub-boxes of the grid. | |
Empty cells are indicated by the character '.'. | |
A sudoku puzzle... | |
...and its solution numbers marked in red. | |
Note: | |
The given board contain only digits 1-9 and the character '.'. | |
You may assume that the given Sudoku puzzle will have a single unique solution. | |
The given board size is always 9x9. | |
My code: | |
class Solution: | |
def solveSudoku(self, board): | |
""" | |
:type board: List[List[str]] | |
:rtype: void Do not return anything, modify board in-place instead. | |
""" | |
self.board=board | |
self.nums = {chr(i + ord('1')) for i in range(9)} | |
self.rows = {i : set() for i in range(9)} | |
self.cols = {i : set() for i in range(9)} | |
self.sqrs = {(i,j) : set() for i in range(3) for j in range(3)} | |
for i, row in enumerate(board): | |
for j, col in enumerate(row): | |
if col == '.': continue | |
self.rows[i].add(col) | |
self.cols[j].add(col) | |
self.sqrs[(i//3,j//3)].add(col) | |
self.flag=False | |
self.find(0,0) | |
def add(self,i,j,n): | |
col=n | |
self.rows[i].add(col) | |
self.cols[j].add(col) | |
self.sqrs[(i//3,j//3)].add(col) | |
self.board[i][j] = n | |
def rm(self,i,j,n): | |
col=n | |
self.rows[i].discard(col) | |
self.cols[j].discard(col) | |
self.sqrs[(i//3,j//3)].discard(col) | |
self.board[i][j] = '.' | |
def options(self, i, j): | |
return self.nums - self.rows[i] - self.cols[j] - self.sqrs[(i//3,j//3)] | |
def find(self,i,j): | |
if j>8: | |
return self.find(i+1,0) | |
if i>8: | |
self.flag=True | |
else: | |
if self.board[i][j] != '.': return self.find(i, j+1) | |
opts = self.options(i, j) | |
if not opts: return | |
for n in opts: | |
self.add(i, j, n) | |
self.find(i, j+1) | |
if self.flag: return | |
self.rm(i, j, n) | |
Solution: | |
https://leetcode.com/problems/sudoku-solver |