import time
# Helper function to get the sequence of positive unshaded values for a line
def get_unshaded_values(line_values, line_shaded):
"""
Collects the sequence of positive values from unshaded cells in a line.
Args:
line_values: List of integer values in the cells of the line.
line_shaded: List of boolean states (True if shaded, False if unshaded)
for the cells in the line.
Returns:
A list of positive integers representing the values in unshaded cells, in order.
"""
values = []
for val, shaded in zip(line_values, line_shaded):
if not shaded and val > 0:
values.append(val)
return values
# Helper function to get the sequence of unshaded block lengths for a line
def get_block_lengths(line_shaded):
"""
Calculates the lengths of contiguous blocks of unshaded cells in a line.
Args:
line_shaded: List of boolean states (True if shaded, False if unshaded)
for the cells in the line.
Returns:
A list of positive integers representing the lengths of unshaded blocks, in order.
"""
lengths = []
current_block_length = 0
for shaded in line_shaded:
if not shaded:
current_block_length += 1
else:
if current_block_length > 0:
lengths.append(current_block_length)
current_block_length = 0
if current_block_length > 0:
lengths.append(current_block_length)
return lengths
# Check if a line (row or column) is valid according to the Internono rule
def is_line_valid(line_values, line_shaded):
"""
Checks if a line satisfies the rule: sequence of positive unshaded values
equals the sequence of unshaded block lengths.
Args:
line_values: List of integer values in the cells of the line.
line_shaded: List of boolean states (True if shaded, False if unshaded)
for the cells in the line.
Returns:
True if the line is valid, False otherwise.
"""
values = get_unshaded_values(line_values, line_shaded)
lengths = get_block_lengths(line_shaded)
return values == lengths
# Check if the entire grid is valid
def is_grid_valid(grid_values, shaded_grid):
"""
Checks if the entire grid is valid by validating all rows and columns.
Args:
grid_values: The 2D list representing the puzzle grid values.
shaded_grid: The 2D boolean list representing the shading state.
Returns:
True if the grid is valid, False otherwise.
"""
size = len(grid_values)
# Check rows
for r in range(size):
# A line is only valid if all its cells have been decided (not None)
if not all(cell is not None for cell in shaded_grid[r]):
return False # Cannot validate a partially decided line with this rule
if not is_line_valid(grid_values[r], shaded_grid[r]):
return False
# Check columns
for c in range(size):
col_values = [grid_values[r][c] for r in range(size)]
col_shaded = [shaded_grid[r][c] for r in range(size)]
# A line is only valid if all its cells have been decided (not None)
if not all(cell is not None for cell in col_shaded):
return False # Cannot validate a partially decided line with this rule
if not is_line_valid(col_values, col_shaded):
return False
return True
# Backtracking solver for Internono
def solve_internono(grid_values):
"""
Solves the Internono puzzle using backtracking.
Args:
grid_values: The 2D list representing the puzzle grid values.
Returns:
A 2D boolean list representing the shaded state if a solution is found,
or None if no solution exists.
"""
size = len(grid_values)
# Initialize shaded grid: True for 0s (mandatory shaded), None for others (undecided)
shaded_grid = [[(grid_values[r][c] == 0) if grid_values[r][c] == 0 else None
for c in range(size)] for r in range(size)]
# Collect list of undecided cells (where grid value > 0)
undecided_cells = []
for r in range(size):
for c in range(size):
if shaded_grid[r][c] is None:
undecided_cells.append((r, c))
def backtrack(cell_index):
"""Recursive backtracking function."""
if cell_index == len(undecided_cells):
# All undecided cells have been assigned True/False.
# The grid is fully decided (no None values).
# Now, check if the full grid is valid.
return is_grid_valid(grid_values, shaded_grid)
r, c = undecided_cells[cell_index]
# --- Pruning Check ---
# Before trying options for the current cell, check if the current *partial*
# assignment makes any *already fully decided* lines invalid.
# (Note: In this specific implementation, a line only becomes "fully decided"
# when the last 'None' cell in that line is assigned. So we only need to
# check lines that *just* became fully decided, or check all lines at the end.
# The `is_grid_valid` function already checks all lines and ensures they are fully decided).
# A more aggressive prune would try to infer contradictions from partial lines,
# but that's complex with the value-equals-length rule.
# Let's stick to checking full lines only for validity for correctness,
# potentially sacrificing speed. The check in `is_grid_valid` handles this.
# If we wanted to prune early when a line becomes full *during* backtracking,
# we'd add checks here, but they must only trigger when the line is *fully* decided.
# The current structure of `is_grid_valid` implicitly handles this by returning False
# if any line still has `None`.
# --- Recursive Steps ---
# Option 1: Shade the current cell (set to True)
shaded_grid[r][c] = True
if backtrack(cell_index + 1):
return True # Found a solution down this path
# Option 2: Unshade the current cell (set to False)
# Note: An unshaded cell must have a positive value according to the rules.
# We only put cells with grid_values > 0 in undecided_cells, so this is safe.
shaded_grid[r][c] = False
if backtrack(cell_index + 1):
return True # Found a solution down this path
# Backtrack: If neither option led to a solution, reset the cell state
# to undecided (None) before returning False. This restores the state
# for parent calls exploring other branches.
shaded_grid[r][c] = None
return False
# Start the backtracking process from the first undecided cell
if backtrack(0):
# If backtrack returns True, a solution is found and stored in shaded_grid.
# Return the final shaded grid (which should have no None values left).
return shaded_grid
else:
# No solution found
return None
# The puzzle instance
big_test = [
[0,2,0,0,0, 0,0,2,0,1],
[2,1,0,1,0, 2,0,0,0,1],
[0,0,0,1,0, 1,0,0,2,0],
[2,1,0,1,0, 0,0,0,0,0],
[0,1,0,0,0, 0,1,1,1,3],
[1,2,0,0,0, 0,0,1,2,0],
[1,0,0,4,0, 2,2,0,0,0],
[0,0,2,0,3, 1,1,1,0,0],
[0,0,2,0,0, 0,0,1,0,0],
[0,3,2,0,0, 0,1,0,0,0],
]
print("Solving Internono puzzle...")
start_time = time.time()
solution_grid = solve_internono(big_test)
end_time = time.time()
# Print the solution
if solution_grid:
print("Solution Found:")
# Convert boolean grid to S/U representation for printing
result_representation = []
for r in range(len(solution_grid)):
row_repr = ""
for c in range(len(solution_grid[0])):
if solution_grid[r][c] is True:
row_repr += "S " # Shaded
elif solution_grid[r][c] is False:
row_repr += "U " # Unshaded
else:
row_repr += "? " # Should not happen in a valid solution
result_representation.append(row_repr.strip())
for row_str in result_representation:
print(row_str)
print(f"\nSolved in {end_time - start_time:.4f} seconds.")
# Verification: Check all rows and columns in the found solution
print("\nVerification of the solution rules:")
size = len(big_test)
all_lines_valid = True
for r in range(size):
row_values = big_test[r]
row_shaded = solution_grid[r]
values = get_unshaded_values(row_values, row_shaded)
lengths = get_block_lengths(row_shaded)
match = (values == lengths)
print(f"Row {r}: Unshaded Values={values}, Block Lengths={lengths} -> Match: {match}")
if not match:
all_lines_valid = False
for c in range(size):
col_values_list = [big_test[r][c] for r in range(size)]
col_shaded_list = [solution_grid[r][c] for r in range(size)]
values = get_unshaded_values(col_values_list, col_shaded_list)
lengths = get_block_lengths(col_shaded_list)
match = (values == lengths)
print(f"Col {c}: Unshaded Values={values}, Block Lengths={lengths} -> Match: {match}")
if not match:
all_lines_valid = False
if all_lines_valid:
print("\nAll rows and columns satisfy the Internono rule.")
else:
print("\nVerification FAILED: Some lines do not satisfy the rule.")
else:
print("No solution found.")