problems / 279

Suki Sniffs the Garden in a Spiral

easy matrix simulation arrays 1000 ms · 256 MB

Suki Sniffs the Garden in a Spiral

Suki, the curly black dog with the grey beard, inspects the vegetable garden every morning, and she always does it in the same order. The garden is a grid of R rows and C columns of beds, and each bed holds one plant, written as a lowercase letter.

Suki starts at the top-left bed. She walks right along the top row, then down the rightmost column, then left along the bottom row, then up the leftmost column. That is the outer ring of the garden. Then she steps inside and sniffs the next ring the same way: right, down, left, up. She keeps spiralling inward until she has sniffed every bed exactly once. If what's left is a single row or a single column, she just walks along it (right for a row, down for a column).

Print the letters of the beds in the order Suki sniffs them.

Input

The first line contains two integers R and C (1 ≤ R, C ≤ 1000): the number of rows and columns.

Each of the next R lines contains a string of exactly C lowercase English letters: one row of the garden, from top to bottom.

Output

Print one line with a string of R·C letters: the plants in the order Suki visits their beds.

Notes

In the first example the garden is

abc
def
ghi

Suki sniffs abc along the top, fi down the right side, hg back along the bottom, d going up, and finally e in the middle: abcfihgde.

In the second example the garden has 3 rows and 4 columns. After the outer ring (abcd, hl, kji, e), only the middle row fg is left, which she walks from left to right. Each bed is sniffed exactly once, so the answer has 12 letters.

Example 1

Input

3 3
abc
def
ghi

Output

abcfihgde

Example 2

Input

3 4
abcd
efgh
ijkl

Output

abcdhlkjiefg

Hints · reveal one at a time if you're stuck

Hint 1

Keep track of the rectangle of beds Suki hasn't sniffed yet. What happens to its edges after she walks along the top row?

Hint 2

Store four boundaries: top, bottom, left and right. After walking an edge, move that boundary one step inward. Before walking the bottom row or the left column, check that the rectangle is still non-empty, or a single leftover row or column gets sniffed twice.

report an issue Prefer your own editor? sooks prep 279 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.