-2

Let's say I have a board like this

. . x . . .
. . . . . .
. . x . . x

x is used box and '.' are free. I need to put triomines to fill all the area, so there will be no free cells. Triomines are L-shaped, and I mark same triomino with the same number.

So the solution could be like this:

1 1 x 3 5 5
1 2 3 3 4 5
2 2 x 4 4 x

What the possible backtracking python algorithm might be?

lenik
  • 23,228
  • 4
  • 34
  • 43

1 Answers1

2

algorithm is quite simple, first we get a list of the cells available in this board configuration, basically, list all the possible cells minus the forbidden ones.

then we make a solution step by iterating over the available cell list and trying to fit a triomino piece into this particular cell position, using 4 possible orientations (available cell is the corner, we have 4 orientations because of rotation).

if the piece fits, increase the step, remove occupied cells from the list and try solving again, until there are no cells available -- that means the whole board is covered.

#!/usr/bin/env python

solution = {}

orientations = [(1,1),(1,-1),(-1,1),(-1,-1)]    # 4 possible orientations

def solve( avl, step ) :
    if not len(avl) :
        print 'done!'
        return True

    for i,j in avl :
        for oi,oj in orientations :
            if (i+oi,j) in avl and (i,j+oj) in avl :
                occupied = [(i,j),(i+oi,j),(i,j+oj)]
                # remove occupied from available, increase step and keep solving
                if solve( [a for a in avl if a not in occupied], step + 1 ) :
                    for occ in occupied :
                        solution[occ] = step
                    return True

# initial conditions for this configuration
#
# . . x . . .
# . . . . . .
# . . x . . x

X_SIZE, Y_SIZE = 6, 3
forbidden_cells = [(0,2),(2,2),(2,5)]

if __name__ == '__main__' :
    available = []

    # fill the available cells list
    for i in range(Y_SIZE) :
        for j in range(X_SIZE) :
            if (i,j) not in forbidden_cells :
                available.append( (i,j) )

    # print the original problem
    for i in range(Y_SIZE) :
        for j in range(X_SIZE) :
            print '.' if (i,j) in available else 'x',
        print

    # solve away!
    if solve( available, 1 ) :
        for i in range(Y_SIZE) :
            for j in range(X_SIZE) :
                print solution[(i,j)] if (i,j) in available else 'x',
            print
    else :
        print 'sorry, no solution found'

The output is:

$ ./triomines.py 
. . x . . .
. . . . . .
. . x . . x
done!
1 1 x 3 2 2
1 4 3 3 5 2
4 4 x 5 5 x
$
lenik
  • 23,228
  • 4
  • 34
  • 43
  • 2
    I need to do this, but this algorithm is very inefficient. It take too long time to solve even a little bigger area. How can this be done in more effective way ? – user2466601 May 23 '14 at 12:23