simple and short python solver


  • 0
    B
    class Solution(object):
        def solveSudoku(self, board):
            """
            :type board: List[List[str]]
            :rtype: void Do not return anything, modify board in-place instead.
            """
            def valid(x, y):
                h, v, c = {}, {}, {}
                for i in range(9):
                    vh, vv, vc = listBoard[y][i], listBoard[i][x], listBoard[3 * (y//3) + (i//3)][3 * (x//3) + (i%3)]
                    if vh != '.' and vh in h or \
                       vv != '.' and vv in v or \
                       vc != '.' and vc in c:
                        return False
                    h[vh] = v[vv] = c[vc] = True
                return True
                
            def solve(index):
                if index == len(spaces):
                    return True
                x, y = spaces[index]
                for c in '123456789':
                    listBoard[y][x] = c
                    if valid(x, y) and solve(index + 1):
                        return True
                    listBoard[y][x] = '.'
    
            spaces = [(x, y) for x in range(9) for y in range(9) if board[y][x] == '.']
            listBoard = [list(line) for line in board]
            solve(0)
            for i in range(9):
                board[i] = ''.join(listBoard[i])
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.