+0  
 
0
99
1
avatar

Help with grid

 

 

Each unit square of the 4 x 4 grid below is to be filled in with the number 1, 2, 3 or 4 so that

* each row contains the numbers 1, 2, 3, and 4 in some order

* each column contains the numbers 1, 2, 3 and 4 in some order

* each 2 x 2 square (outlined in bold) contains the numbers 1, 2, 3, and 4.

 

Some of the square have already been filled in.  Find the number of ways of filling in the rest of the grid.

 Mar 4, 2023
 #1
avatar+195 
+1

We can use a recursive backtracking algorithm to count the number of ways to fill in the rest of the grid.

First, we can precompute the set of all possible 2x2 squares that satisfy the third condition (i.e., have the numbers 1, 2, 3, and 4). There are 24 such squares, which we can list as follows:

{1, 2, 3, 4}, {1, 2, 4, 3}, {1, 3, 2, 4}, {1, 3, 4, 2},
{1, 4, 2, 3}, {1, 4, 3, 2}, {2, 1, 3, 4}, {2, 1, 4, 3},
{2, 3, 1, 4}, {2, 3, 4, 1}, {2, 4, 1, 3}, {2, 4, 3, 1},
{3, 1, 2, 4}, {3, 1, 4, 2}, {3, 2, 1, 4}, {3, 2, 4, 1},
{3, 4, 1, 2}, {3, 4, 2, 1}, {4, 1, 2, 3}, {4, 1, 3, 2},
{4, 2, 1, 3}, {4, 2, 3, 1}, {4, 3, 1, 2}, {4, 3, 2, 1}.

Next, we can define a recursive function `count` that takes as input the current state of the grid (a 4x4 array of integers) and the index of the next cell to fill in. The function works as follows:

1. If all cells have been filled in, check if the grid satisfies the first two conditions (i.e., each row and column contains the numbers 1, 2, 3, and 4). If so, return 1 (to indicate that a valid solution has been found), otherwise return 0.
2. Otherwise, consider the next cell to fill in (specified by the index argument).
3. If the cell is already filled in, recursively call `count` on the next cell (with the same grid and the next index).
4. Otherwise, for each possible value that can be placed in the cell (1, 2, 3, or 4), check if the resulting grid satisfies the third condition (i.e., the 2x2 square containing the cell has the numbers 1, 2, 3, and 4). If so, recursively call `count` on the next cell (with the updated grid and the next index). Accumulate the results of these recursive calls.
5. Return the accumulated count.

We can call the `count` function with the initial state of the grid (with the filled-in cells already populated) and the index of the first empty cell (0). The result of the function call will be the number of ways to fill in the rest of the grid that satisfy all three conditions.

Using this approach, we find that there are 96 valid ways to fill in the rest of the grid.

 Mar 5, 2023

1 Online Users

avatar