How does Python determine if sudoku is legal
- 2020-05-10 18:23:55
- OfStack
introduce
The sudoku may have filled in only a few Numbers, and the missing ones are represented by.
Matters needing attention
A legitimate sudoku (only partially filled) is not necessarily solvable. We just need to make the filled space valid.
The collapse of the train of thought
The sudoku was preprocessed according to rows, columns and blocks, and then judged to be legal or not.
Derivation using Python expressions, anonymous functions and
all
Functions are easy to handle.
code
class Solution:
# @param board, a 9x9 2D array
# @return a boolean
def isValidSudoku(self, board):
rows = [list(lst[::]) for lst in board]
columns = [[lst[idx] for lst in board] for idx in range(9)]
blocks_origin = [board[row][column] for x in [[0, 1, 2], [3, 4, 5], [6, 7, 8]] for y in [[0, 1, 2], [3, 4, 5], [6, 7, 8]] for row in x for column in y] # using 1 Some tricks store data in blocks directly
blocks = [[blocks_origin[row * 9 + column] for column in range(9)] for row in range(9)]
check = lambda lst: all([lst.count(x) == 1 for x in lst if x != '.']) # judge 1 A list of records arranged in a certain way 9 Is it legal
return all([check(x) for style in (rows, columns, blocks) for x in style]) # 1 Step out
summary
Can not use the body as much as possible not to use the body cycle, the above is the whole content of this article, I hope to help you with your study and work, if you have questions you can leave a message to communicate.