LEETCODE —— Sudoku Solver

 

Write a program to solve a Sudoku puzzle by filling the empty cells.

Empty cells are indicated by the character '.'.

You may assume that there will be only one unique solution.

A sudoku puzzle...

 

...and its solution numbers marked in red.

 

 

 

 1 class Solution(object):
 2     def validset(self ):
 3         s='123456789'
 4         return set(s)
 5 
 6     def initTbl(self, tbl, board):
 7         for i in range(9):
 8             for j in range(9):
 9                 if board[i][j] == '.':
10                     tbl[(i,j)]=[]
11 
12 
13     def solveSudoku(self, board):
14         """
15         :type board: List[List[str]]
16         :rtype: bool
17         """
18         resultTbl={}
19         visited=[]
20         self.initTbl(resultTbl, board)
21         reuse=False
22         unvisited = resultTbl.keys()
23         unvisited.sort()
24         unvisited.reverse()
25 
26         while unvisited != []:
27             (x, y) = unvisited.pop()
28             if reuse==False:
29                 resultTbl[(x,y)] = self.possibleValues((x,y), board)
30                 if resultTbl[(x,y)] == None: # invalid sudoku
31                     print False
32                     break
33 
34             if len( resultTbl[(x,y)] ) == 0: # DEAD END, BACKTRACK
35                 unvisited.append((x, y))
36                 if visited != []:
37                     reuse=True
38                     prev=visited.pop()
39                     unvisited.append(prev)
40                     x=prev[0]
41                     y=prev[1]
42                     board[x][y]='.'
43                 else:
44                     break
45                 continue
46             board[x][y]=resultTbl[(x,y)].pop()
47             visited.append((x,y))
48             reuse=False
49         for line in board:
50             if '.' in line:
51                 print False
52 
53 
54     def possibleValues(self, coord, board):
55         vals = {'.':0}
56         for i in range(1,10): #init
57             vals[str(i)]=0
58 
59         for y in range(0,9):
60             node=board[coord[0]][y]
61             vals[node]+=1
62             if vals[node]>1 and node!='.': return None
63         for x in range(0,9):
64             node=board[x][coord[1]]
65             vals[node]+=1
66             if vals[node] > 2 and node!='.': return None
67         x = coord[0]/3*3
68         y = coord[1]/3*3
69         for i in range(x, x+3):
70             for j in range(y, y+3):
71                 node=board[i][j]
72                 vals[node]+=1
73                 if vals[node]>3 and node!='.': return None
74         s = set()
75         for k in vals.keys():
76             if vals[k]>=1: s.add(k)
77         return self.validset() - s

 

-- Scott, Programmer in Beijing [If you can’t explain it to a six year old, you don’t understand it yourself. —Albert Einstein ]
posted @ 2015-12-21 14:33  ScottGu  阅读(186)  评论(0编辑  收藏  举报