#K11241. Find Lexicographically Smallest Word in the Grid
Find Lexicographically Smallest Word in the Grid
Find Lexicographically Smallest Word in the Grid
You are given a grid of characters with R rows and C columns. In this grid, a word is defined as any contiguous sequence of exactly two characters that appears either horizontally (from left to right) or vertically (from top to bottom). Your task is to find and print the lexicographically smallest word from the grid.
Formally, for each test case, if the grid is represented as a two-dimensional array \(grid\) with \(R\) rows and \(C\) columns, then a word \(w\) can be obtained by:
- Extracting two consecutive characters from any row, i.e. \(w = grid[i][j]\,grid[i][j+1]\) for any valid \(i\) and \(j\) such that \(0 \le j < C-1\).
- Extracting two consecutive characters from any column, i.e. \(w = grid[i][j]\,grid[i+1][j]\) for any valid \(j\) and \(i\) such that \(0 \le i < R-1\).
You must consider both horizontal and vertical words and choose the one that is smallest according to lexicographical order.
inputFormat
The input begins with a single integer \(T\) representing the number of test cases. Each test case is described as follows:
- The first line of each test case contains two integers \(R\) and \(C\) — the number of rows and columns in the grid.
- The next \(R\) lines each contain a string of length \(C\), representing a row of the grid.
All inputs are read from standard input (stdin).
outputFormat
For each test case, output the lexicographically smallest word found in the grid on a new line. The output should be written to standard output (stdout).
## sample1
3 3
abc
def
ghi
ab
</p>