Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

How to get this code to actually print out a grid to show the solution of the puzzle: def solve ( lights , current _

How to get this code to actually print out a grid to show the solution of the puzzle:
def solve(lights, current_depth, max_depth, presses=[]):
"""Recursive backtracking search with depth limit."""
if current_depth > max_depth:
return
if all_lights_are_off(lights):
print(f"Solution found in {current_depth} steps:")
for row, col in presses:
print(f"Press button at ({row},{col})")
exit(
# Try all possible button presses
for row in range(len(lights)):
for col in range(len(lights[0])):
new_presses = presses +[(row, col)] # Record the press in a new list
lights_copy = flip(lights, row, col) # Create a copy to avoid modifying the original grid
solve(lights_copy, current_depth +1, max_depth, new_presses) # Pass the updated presses list
def all_lights_are_off(lights):
"""Checks if all lights in the grid are off."""
for row in lights:
for light in row:
if light:
return False
return True
def flip(lights, row, col):
N = len(lights)
lights[row][col]=1- lights[row][col]
# Toggle neighbors
if row >0:
lights[row -1][col]=1- lights[row -1][col]
if row < N -1:
lights[row +1][col]=1- lights[row +1][col]
if col >0:
lights[row][col -1]=1- lights[row][col -1]
if col < N -1:
lights[row][col +1]=1- lights[row][col +1]
return lights
def lights_out_solver(N):
lights =[[1]*4 for _ in range(4)] # All lights are initially ON
max_depth =0
while True:
print("Searching with max_depth =", max_depth)
solve(lights,0, max_depth, [])
max_depth +=1
# Example usage with a 3x3 grid
lights_out_solver(3)
# If you get here, there was no solution on this path: backtrack

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Hands-On Database

Authors: Steve Conger

2nd Edition

0133024415, 978-0133024418

More Books

Students also viewed these Databases questions