#K88257. Word Square Formation

    ID: 37268 Type: Default 1000ms 256MiB

Word Square Formation

Word Square Formation

You are given a list of words, all having the same length. Your task is to determine if it is possible to arrange some of these words into a word square. A word square is a set of words arranged in an n×n grid such that the word in the i-th row is the same as the word in the i-th column for all 0 ≤ i < n. If possible, output one valid word square; otherwise, output an empty list.

For example, consider the words ["area", "lead", "wall", "lady", "ball"]. One valid word square is:

wall
area
lead
lady

If no valid word square exists, output [].

Note: The letters at each corresponding row and column must match exactly. Reusing words is allowed as long as they appear in the input list.

inputFormat

The input is read from stdin and is formatted as follows:

  • The first line contains an integer n, representing the number of words.
  • The next n lines each contain one word.

All words are guaranteed to be of the same length.

outputFormat

The output should be written to stdout as follows:

  • If a valid word square exists, print each word of the square on a new line in order.
  • If no valid word square exists, print [] (without quotes).
## sample
5
area
lead
wall
lady
ball
wall

area lead lady

</p>