Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 70399ca

Browse files
authoredOct 21, 2018
Add files via upload
1 parent 3f5b6d8 commit 70399ca

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
 

‎Sudoku Solver/Sudoku_Solver.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# 532ms 55.56%
2+
class Solution:
3+
def solveSudoku(self, board):
4+
"""
5+
:type board: List[List[str]]
6+
:rtype: void Do not return anything, modify board in-place instead.
7+
"""
8+
self.board = board
9+
self.solve()
10+
11+
def find_first_unassigned(self):
12+
"""
13+
14+
顺序查找第一个还没有被赋值的坐标
15+
"""
16+
for i in range(9):
17+
for j in range(9):
18+
if self.board[i][j] == '.':
19+
return i, j
20+
# 如果全部被赋值,则返回一个哑变量
21+
return -1, -1
22+
23+
def judge(self, row, column, value):
24+
"""
25+
26+
用来判断给定坐标的值是否合理
27+
"""
28+
# 首先判断行
29+
if value in self.board[row]:
30+
return False
31+
# 然后判断列
32+
for i in range(9):
33+
if self.board[i][column] == value:
34+
return False
35+
# 最后判断宫
36+
for i in range(row // 3 * 3, row // 3 * 3 + 3):
37+
for j in range(column // 3 * 3, column // 3 * 3 + 3):
38+
if self.board[i][j] == value:
39+
return False
40+
# 如果都通过了测试,则返回真
41+
return True
42+
43+
def solve(self):
44+
row, column = self.find_first_unassigned()
45+
if row == - 1 and column == -1:
46+
return True
47+
for num in ["1","2","3","4","5","6","7","8","9"]:
48+
if self.judge(row, column, num):
49+
self.board[row][column] = num
50+
if self.solve():
51+
return True
52+
self.board[row][column] = '.'
53+
return False

0 commit comments

Comments
 (0)
Please sign in to comment.