File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change @@ -143,3 +143,48 @@ var solveSudoku = function (board) {
143143 }
144144};
145145```
146+
147+ Python Code
148+
149+ ``` py
150+ class Solution (object ):
151+ def solveSudoku (self , board ):
152+ """
153+ :type board: List[List[str]]
154+ :rtype: None Do not return anything, modify board in-place instead.
155+ """
156+ rows = [[False ]* 9 for _ in range (9 )]
157+ cols = [[False ]* 9 for _ in range (9 )]
158+ boxes = [[[False ]* 9 for _ in range (3 )] for _ in range (3 )]
159+
160+ def mark (x , y , n , status ):
161+ rows[x][n] = cols[y][n] = boxes[x // 3 ][y // 3 ][n] = status
162+
163+ def valid (x , y , n ):
164+ return (not rows[x][n]) and (not cols[y][n]) and (not boxes[x // 3 ][y // 3 ][n])
165+
166+ def dfs (pos ):
167+ if pos >= len (spaces): return True
168+
169+ x, y = spaces[pos]
170+ for n in range (9 ):
171+ if not valid(x, y, n): continue
172+
173+ board[x][y] = str (n + 1 )
174+ mark(x, y, n, True )
175+
176+ if dfs(pos + 1 ): return True
177+
178+ mark(x, y, n, False )
179+
180+ spaces = []
181+ for x in range (9 ):
182+ for y in range (9 ):
183+ cell = board[x][y]
184+
185+ if cell == ' .' :
186+ spaces.append((x, y))
187+ else :
188+ mark(x, y, int (cell) - 1 , True )
189+ dfs(0 )
190+ ```
You can’t perform that action at this time.
0 commit comments