Consider a square $$n \times n$$ grid in which each cell is labeled. Labels are either integers (int) or strings (str). Cells with the same label form a group.

Labeling the cells results in an equidivision if each group has $$n$$ cells and is connected.

Two cells are contiguous when they have a common side. A group is connected if all its cells form a contiguous unit.

equidivision

The cells of these two $$5 \times 5$$ grids have been labeled with integers in the range 1 to 5. All groups have 5 cells, but all groups are connected only in the left grid. The left grid thus is an equidivision, where the right grid is not: groups 4 and 5 are not connected.

Assignment

We represent a square grid of labeled cells as a sequence (list or tuple) containing the rows of the grid, listed from top to bottom. Each row is itself represented as a sequence (list or tuple) containing the labels (int or str) of the cells on that row, listed from left to right.

The position of a cell in a grid is described by a tuple $$(r, c)$$, with $$r$$ the row number (int) and $$c$$ the column number (int) of the cell in the grid. Rows are indexed top to bottom starting from zero, and columns are indexed left to right starting from zero.

Your task:

Example

>>> grid = [[1, 1, 1], [2, 2, 3], [2, 3, 3]]
>>> groups(grid)
{1: {(0, 1), (0, 0), (0, 2)}, 2: {(2, 0), (1, 0), (1, 1)}, 3: {(1, 2), (2, 1), (2, 2)}}

>>> grid = [[1, 1, 1, 5, 5], [2, 1, 5, 5, 4], [2, 1, 5, 4, 4], [2, 2, 4, 4, 3], [2, 3, 3, 3, 3]]
>>> groups(grid)
{1: {(0, 1), (0, 0), (0, 2), (2, 1), (1, 1)}, 2: {(3, 0), (2, 0), (1, 0), (3, 1), (4, 0)}, 3: {(4, 1), (4, 4), (3, 4), (4, 3), (4, 2)}, 4: {(3, 2), (2, 3), (2, 4), (1, 4), (3, 3)}, 5: {(1, 2), (0, 3), (1, 3), (2, 2), (0, 4)}}

>>> isconnected({(1, 2), (1, 3), (2, 2), (0, 3), (0, 4)})
True
>>> isconnected({(1, 2), (1, 4), (2, 2), (0, 3), (0, 4)})
False

>>> grid = [[1, 1, 1], [2, 2, 3], [2, 3, 3]]
>>> isequidivision(grid)
True

>>> grid = [[1, 1, 1], [2, 2, 3], [3, 3, 2]]
>>> isequidivision(grid)
False

>>> grid = [[1, 1, 1, 5, 5], [2, 1, 5, 5, 4], [2, 1, 5, 4, 4], [2, 2, 4, 4, 3], [2, 3, 3, 3, 3]]
>>> isequidivision(grid)
True