#P9417. Template Tiling
Template Tiling
Template Tiling
You are given an n×m grid of lowercase letters. You have to design two physical templates, both containing an identical string S of length l (the template length). One template is horizontal (of size 1 × l, which when stamped prints the string from left to right) and the other is vertical (of size l×1, which when stamped prints the string from top to bottom). Using only these two templates (you may stamp as many times as you wish, in any order, but without overlapping stamps and with no cell left unprinted), you must be able to exactly reproduce the given character grid.
More formally, you must choose a template length l (1 ≤ l ≤ min(n, m)) and a string S of length l such that it is possible to partition the grid into disjoint segments, each of which is either a contiguous horizontal segment of length l (printed using the horizontal template) or a contiguous vertical segment of length l (printed using the vertical template), and for every such segment the characters appear exactly as in S (in the natural order, i.e. left‐to‐right for a horizontal stamp and top‐to‐bottom for a vertical stamp). Note that the templates cannot be rotated, and the string on both templates must be identical.
Your task is to output all possible template lengths l for which such a tiling exists.
Note: It is not required that one type of stamping (horizontal or vertical) covers the entire grid by itself. You are allowed to mix the two kinds of stamp placements so that the grid is perfectly covered without overlaps or gaps.
inputFormat
The first line contains two integers n and m (1 ≤ n, m ≤ 10) representing the number of rows and columns of the grid. The following n lines each contain a string of length m consisting of lowercase letters, representing the grid.
outputFormat
Output all possible template lengths l (in increasing order) for which it is possible to cover the grid using a combination of horizontal (1 × l) and vertical (l × 1) stamps (all printing an identical string S) as described. Separate the lengths by a single space. If there is no valid template length, output an empty line.
sample
2 2
aa
aa
1 2