Some backstory
I made a Sudoku solver which works if any given cell has only 1 option to fill in it's given row/column/group. But this solver doesn't work if the options are above 1, so I tried to make a recursive solver which takes turn for every possible option in each cell, I tried several methods to branch the choices, but I can't find a way to make it go back to a state and take the next option. My program seem to be always taking the same path.
My code work as follows:
It start by find every possible moves for every cell
Then it sort them by the least amount of options.
If there's a length 1 option in a given cell it fills it and restart,
If not, it will loop over the options
Ideally it would keep going until exhaustion and go back to the last option chosen and take the other one. But it's not doing that, it is repeating itself.
What I'm trying to do now:
After some research I found that what I'm trying to do is called Depth-First-Search,
I found this implementation of the DFS, however I'm not being able to implement it in my program.
Here's my attempt:
def best_moves():
# get_possible_moves() returns a list of all the available moves for every cell
# sorting it and taking the first element will get the one
# that has the least amount options
return [move for move in sorted(board.get_possible_moves())[0]]
def get_next_nodes(move):
board.make_this_move(move)
return best_moves()
def dfs(graph, start):
visited, stack = set(), [start]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.add(vertex)
nodes = []
for move in graph[vertex]:
nodes.extend(get_next_nodes(move))
nodes = [node for node in nodes if node not in visited]
stack.extend(nodes)
return visited
b = Board(puzzle_hard)
b.create_board()
graph = {'root':best_moves()}
dfs(graph,'root')
It gives:
Traceback (most recent call last):
File "C:\Users\user\Documents\python\sudoku\sudoku_solver.py", line 171, in <module>
dfs(graph,'root')
File "C:\Users\user\Documents\python\sudoku\sudoku_solver.py", line 162, in dfs
for move in graph[vertex]:
KeyError: <__main__.PossibleMove instance at 0x0223DB48>
PossibleMove is a class that I made to handle the possible moves for a given cell. I could try to add it to the graph, but in order to do that I need to search it again, and I can't do that because i'm in the middle of the DFS.
tl;dr
How to implement DSF without having all the nodes in the graph beforehand.