Short solution in Python.. why not working?


  • 0
    C
    class Solution(object):
        def solveSudoku(self, board):
            """
            :type board: List[List[str]]
            :rtype: void Do not return anything, modify board in-place instead.
            """
            choices = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
            self.solver(0, choices, board)
    
        def solver(self, pos, choices, board):
            if pos >= 81:
                return True
            i = pos / 9;
            j = pos % 9;
    
            if board[i][j] != '.':
                return self.solver(pos + 1, choices, board)
            else:
                for c in choices:                
                    if self.isValid(board, i, j, c):
                        board[i][j] = c
                        if self.solver(pos + 1, choices, board):
                            return True
                        else:
                            board[i][j] = '.'
                
                return False
    
        def isValid(self, board, i, j, c):
            if c in board[i][:]:
                return False
            if c in board[:][j]:
                return False
            for k in range(i - i % 3, i - i % 3 + 3):
                for l in range(j - j % 3, j - j % 3 + 3):
                    if board[k][l] == c:
                        return False
            return True
    

    I got wrong answer on this one:

    Input:
    ["..9748...","7........",".2.1.9...","..7...24.",".64.1.59.",".98...3..","...8.3.2.","........6","...2759.."]
    Output:
    ["..9748...","7........",".2.1.9...","..7...24.",".64.1.59.",".98...3..","...8.3.2.","........6","...2759.."]
    Expected:
    ["519748632","783652419","426139875","357986241","264317598","198524367","975863124","832491756","641275983"]

  • 0
    D

    because you isVaild function is wrong ,
    if c in board[i][:] you set board[i][j] = c first so the c always in board[i][:], isValid always return False


Log in to reply
 

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