An oceanographic institute deploys square arrays of drifting research buoys, L buoys to a side. Every array is assembled by choosing, for each of the L rows, one L-letter lowercase beacon code from the institute's registry — the same code may be reused in more than one row. An arrangement is considered stable only if, for every index k from 0 to L-1, reading the letters of row k from left to right produces exactly the same string as reading the letters of column k from top to bottom. Given the registry, find every stable arrangement that can be built this way.
m — the number of codes in the registry (1 <= m <= 1000).m space-separated lowercase strings, the registry's codes, each of the same length L (1 <= L <= 5). No two codes in the registry are identical.Print an integer k on the first line — the number of stable arrangements. Then, ordered lexicographically (compare arrangement 1 by its row 0, then row 1, and so on down to row L-1, against arrangement 2's rows in the same way), print each arrangement as its L rows, one code per line, with no separator line between one arrangement and the next. If k is 0, print only the line 0 and nothing else.
a-z only.Example 1
Input
5 area lead wall lady ball
Expected
2 ball area lead lady wall area lead lady
Explanation
Take rows ball, area, lead, lady: column 0 reads b,a,l,l = "ball" (matches row 0); column 1 reads a,r,e,a = "area" (matches row 1); column 2 reads l,e,a,d = "lead" (matches row 2); column 3 reads l,a,d,y = "lady" (matches row 3) — stable. Swapping the first row to wall gives column 0 = "wall", which still matches row 0, and the other columns are unchanged, so it is also stable. These are the only two stable arrangements; sorted lexicographically, ball's arrangement (starting with 'b') comes before wall's (starting with 'w').
Example 2
Input
2 ab ba
Expected
2 ab ba ba ab
Explanation
With rows ab, ba: column 0 reads a,b = "ab" (matches row 0) and column 1 reads b,a = "ba" (matches row 1) — stable. With rows ba, ab: column 0 reads b,a = "ba" (matches row 0) and column 1 reads a,b = "ab" (matches row 1) — also stable. Both single-code-repeated rows (ab,ab) and (ba,ba) fail because their first column would need to read "aa" or "bb", which is not what row 0 spells. Sorted lexicographically, "ab" then "ba" comes before "ba" then "ab".
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →