Question: Using backtracking, solve this problem in Python: Lights Out Another classic puzzle. You're given a N x N grid of button lights, all of which
Using backtracking, solve this problem in Python:
Lights Out
Another classic puzzle. You're given a N x N grid of button lights, all of which are initially ON Pressing a button toggles the state of its four neighbors in the up down, left and right directions.
Example by KL deVries on Medium
Your goal is to find the combination of button presses that turns all the lights OFF. Write a program that uses backtracking with iterative deepening to find the solution.
Modify the basic recursive backtracking search to take additional currentdepth and maxdepth parameters. If the currentdepth exceeds the maxdepth, treat it as a base case and return immediately.
For a given state, there are N possible moves to consider, which correspond to each possible button press.
Consider why iterative deepening is a good strategy for this problem. You're allowed to press each button as many times as you want, so there's no limit on the depth of any path. Left unchecked, you would simply descend the search tree, pressing buttons to create an infinitely long path that might never lead to a solution. Iterative deepening ensures that you consider all button combinations up to a certain depth before exploring deeper paths.
A pseudocode version of the solve method is as follows:
def solvelights currentdepth, maxdepth:
Recursive backtracking solution to the lights out puzzle
# Depth limit reached
if currentdepth maxdepth:
return
# Determine if the current state is a solution
if alllightsareofflights:
printpresses # Print the sequence of button presses that led to the solution
exit
# Consider all of the N N button presses
for row in rangeN:
for col in rangeN:
# Determine the state of pressing button at position row col
lights fliplights row, col
# Keep track of the sequence of button presses
presses.appendrow col
# Recursively search
solvelights currentdepth maxdepth
# Undo the effect of flipping row col to prepare for the next option
lights fliplights row, col
presses.pop
# If you get here, there was no solution on this path: backtrack
You'll need to figure out how to implement the relevant methods alllightsareoff and flip then write an outer function that runs the search for increasing values of maxdepth until it finds a solution.
The pseudocode assumes that you're keeping track of the state of the lights using an N by N list of lists, which is fine. The variables presses is a list that keeps track of the sequence of button presses used to find the solution.
Start with a small grid, say x then try solving for larger grids.
Step by Step Solution
There are 3 Steps involved in it
1 Expert Approved Answer
Step: 1 Unlock
Question Has Been Solved by an Expert!
Get step-by-step solutions from verified subject matter experts
Step: 2 Unlock
Step: 3 Unlock
