Skip to content

Instantly share code, notes, and snippets.

@mgritter
Created April 2, 2023 21:09
Show Gist options
  • Save mgritter/c0d049498a68eea998a62b52c345ddbe to your computer and use it in GitHub Desktop.
Save mgritter/c0d049498a68eea998a62b52c345ddbe to your computer and use it in GitHub Desktop.
How many squares can be filled in the NxN grid such that no 5 orthogonal neighbors are all filled?
from ortools.sat.python import cp_model
import sys
# How many squares can be filled in the 10x10 grid such that no five
# orthogonally-connected squares are all filled?
m = cp_model.CpModel()
size = 10
if len( sys.argv ) == 2:
size = int( sys.argv[1] )
vars = [ [ m.NewIntVar( 0, 1, f"g_{i}_{j}" ) for j in range( size ) ]
for i in range( size ) ]
for i in range( 1, size - 1 ):
for j in range( 1, size - 1 ):
m.Add( vars[i][j] + vars[i-1][j] + vars[i][j-1] + vars[i+1][j] + vars[i][j+1] < 5)
m.Maximize( sum( vars[i][j] for i in range( size ) for j in range( size ) ) )
solver = cp_model.CpSolver()
status = solver.Solve( m )
def show_soln():
for i in range( size ):
print( "".join( str( solver.Value( vars[i][j] ) )
for j in range( size )))
print()
print( sum( solver.Value( vars[i][j] ) for i in range(size) for j in range( size) ) )
if status == cp_model.OPTIMAL:
print( "OPTIMAL" )
show_soln()
elif status == cp_model.FEASIBLE:
print( "FEASIBLE" )
show_soln()
else:
print( "No solution found." )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment