Desiigner
Desiigner

Reputation: 2316

Python sudoku solver

Trying to create my own sudoku solver.

I'm using 0 as blank

The solver is almost done but sometimes it doesn't replace 0. What's the problem here?

def sud(nums):

    for row in nums:
        for n in row:
            if n == 0:
                under = [u_row[row.index(n)] for u_row in sudoku]
                for i in range(1, 10):
                    if i not in row and i not in under:
                        row[row.index(n)] = i

    return nums

nums here is a list with sudoku, for example:

sudoku = [
[0, 0, 6, 0, 5, 4, 9, 0, 0],
[1, 0, 0, 0, 6, 0, 0, 4, 2],
[7, 0, 0, 0, 8, 9, 0, 0, 0],
[0, 7, 0, 0, 0, 5, 0, 8, 1],
[0, 5, 0, 3, 4, 0, 6, 0, 0],
[4, 0, 2, 0, 0, 0, 0, 0, 0],
[0, 3, 4, 0, 0, 0, 1, 0, 0],
[9, 0, 0, 8, 0, 0, 0, 5, 0],
[0, 0, 0, 4, 0, 0, 3, 0, 7]
]

And this is my output for this list:

[2, 3, 6, 8, 5, 4, 9, 1, 7]
[1, 8, 9, 5, 6, 7, 0, 4, 2]
[7, 1, 2, 4, 8, 9, 6, 3, 5]
[3, 7, 6, 2, 9, 5, 4, 8, 1]
[8, 5, 1, 3, 4, 7, 6, 2, 9]
[4, 6, 2, 9, 1, 3, 7, 0, 0]
[5, 3, 4, 6, 2, 7, 1, 9, 8]
[9, 2, 4, 8, 3, 7, 0, 5, 0]
[6, 9, 5, 4, 8, 1, 3, 2, 7]

Upvotes: 0

Views: 743

Answers (1)

Prakhar Londhe
Prakhar Londhe

Reputation: 1471

Your implementation is flawed. What you are doing is, that you put the first number that is not in the row or column in the position. But this is not always the case. There can be multiple such numbers possible.

For example in your input sudoku, the first element can have 2,3,6 and 8 as its initial value.

What you have to do, is that if the final board still contains zeroes, then backtrack to a previous state and try putting another number, and solve recursively for that state.

Read about Backtracking here.

Upvotes: 3

Related Questions