A cool algorithm to check a Sudoku field?

前端 未结 25 1287
清酒与你
清酒与你 2021-01-30 09:19

Does anyone know a simple algorithm to check if a Sudoku-Configuration is valid? The simplest algorithm I came up with is (for a board of size n) in Pseudocode

f         


        
25条回答
  •  忘了有多久
    2021-01-30 09:51

    Here's a nice readable approach in Python:

    from itertools import chain                                                                                            
    
    def valid(puzzle):                                                                                                     
        def get_block(x,y):                                                                                                
            return chain(*[puzzle[i][3*x:3*x+3] for i in range(3*y, 3*y+3)])                                               
        rows = [set(row) for row in puzzle]                                                                                
        columns = [set(column) for column in zip(*puzzle)]                                                                 
        blocks = [set(get_block(x,y)) for x in range(0,3) for y in range(0,3)]                                             
        return all(map(lambda s: s == set([1,2,3,4,5,6,7,8,9]), rows + columns + blocks))         
    

    Each 3x3 square is referred to as a block, and there are 9 of them in a 3x3 grid. It is assumed as the puzzle is input as a list of list, with each inner list being a row.

提交回复
热议问题