#K89367. Lexicographically Smallest Grid
Lexicographically Smallest Grid
Lexicographically Smallest Grid
Given an \(n \times m\) grid of lowercase English letters, you are allowed to perform at most one move by rearranging the letters in any rectangular subgrid. In this problem, the move is equivalent to rearranging all the characters in the grid.
Your task is to produce the lexicographically smallest grid possible. The lexicographical order is defined as follows: for two strings \(s\) and \(t\), \(s\) is lexicographically smaller than \(t\) if there exists an index \(i\) such that for all \(j < i\), \(s_j = t_j\), and \(s_i < t_i\). In LaTeX, this comparison can be expressed as: $$s < t \Leftrightarrow \exists i, \forall j < i,\ s_j = t_j \text{ and } s_i < t_i.$$
To solve the problem, simply sort all characters in the grid and fill the grid row by row with the sorted characters.
inputFormat
The input begins with a line containing two space-separated integers (n) and (m) (1 ≤ n, m ≤ 1000). The following (n) lines each contain a string of exactly (m) lowercase English letters representing the grid.
outputFormat
Output the lexicographically smallest grid possible after the rearrangement. Print (n) lines, each containing a string of length (m).## sample
2 2
ba
dc
ab
cd
</p>