Let's say there's a 2D grid of 1s and 0s, for example -
0 1 0 0
0 0 1 0
0 0 0 1
1 0 0 0
The grid is "collapsed" to form a smaller grid of 1 fewer row and 1 fewer column, so the above example would be "collapsed" to form a grid of 3 rows and 3 columns.
The new values are determined by the following rule -
new_grid[i][j] is dependent on
i) old_grid[i][j],
ii) old_grid[i][j+1],
iii) old_grid[i+1][j]
iv) old_grid[i+1][j+1]
If exactly one of the above values are 1, then new_grid[i][j] will be 1, else 0.
So for the example grid, out of [0][0], [0][1], [1][0] and [1][1]
, only [0][1]
is 1
, so [0][0]
in the new grid will be 1. Similarly, out of [0][1], [0][2], [1][1] and [1][2]
, both [0][1] and [1][2]
are 1
, so [0][1]
in new_grid
will be 0.
The input is given in the form of new_grid
values. I have to find out the number of possible configurations of old_grid
, such that new_grid
is possible through the collapsing rules provided.
My approach
The backtracking solution that I have currently thought of goes like this -
Identify imaginary 2X2 boxes for each 1-valued cell in the old grid which would correspond to the appropriate cell in the new grid.
All of these boxes will contain exactly one cell with value 1, so put 1 in a random cell in each box.
Recursively check if putting 1s in the random cells ensures that each box still retains exactly one cell with value 1.
If a grid configuration is finally obtained where every box contains exactly one cell with value 1, check if the configuration can be "collapsed" to get the new grid.
If not, then repeat the process with a different cell with the value 1.
If there are some cells in the old grid which don't come under any "box", then they are what I have termed as "doesn't-matter" cells.
For example -
1 1
0 0
For the above new_grid
, the old_grid
can be -
1 0 1
0 0 0
0 0 0
or
1 0 1
0 0 0
1 1 1
The last row's cells are "doesn't-matter" cells since they don't come under any 2X2 box and they can all be 1
s or 0
s to be valid configurations (I am thinking that is the extent to which we can flexibly manipulate them, although I am not sure).
My question is this - This algorithm is quite possibly exponential in growth and it will take a lot of time for a grid of say, 50X10
.
Is there any other way to solve this question? Or is there any clever algorithm to not go through every possible configuration in order to count them?