Pretty-Print the Spiral

Compute values on an infinite counterclockwise number spiral and print a rectangular sub-grid with aligned, minimal-width spacing.

Medium5MathMatrixImplementationSimulationNo attempts yetTime limit2sMemory limit128 MB

Statement

There is an infinitely large square grid. Each cell of the grid is identified by a (row, column) pair.

Fill the entire grid with the positive integers arranged in a spiral. First write 1 at row 0, column 0, then write 2 at row 0, column 1. From there the spiral turns counterclockwise, placing the next integer at each step. Part of the filled grid looks like this. Row numbers increase downward and column numbers increase to the right.

    -3 -2 -1  0  1  2  3
    --------------------
-3 |37 36 35 34 33 32 31
-2 |38 17 16 15 14 13 30
-1 |39 18  5  4  3 12 29
 0 |40 19  6  1  2 11 28
 1 |41 20  7  8  9 10 27
 2 |42 21 22 23 24 25 26
 3 |43 44 45 46 47 48 49

Given four integers r1, c1, r2, c2, print the rectangular region whose top-left cell is (r1, c1) and whose bottom-right cell is (r2, c2), formatted "prettily" according to the following rules.

  1. Print one row at a time, from row r1 through row r2 in order.
  2. Separate two numbers in the same row with a single space.
  3. Every printed row must have the same length.
  4. Use as few spaces as possible.
  5. Print every number with the same width, counting any leading spaces.
  6. If a number has fewer digits than the widest number in the region, pad it on the left with spaces to match that width.

Input

The first line contains four integers r1, c1, r2, c2 separated by spaces.

Output

Print the rectangular region prettily according to the rules. The output consists of r2 − r1 + 1 lines.

Constraints

  • −5000 ≤ r1, c1, r2, c2 ≤ 5000
  • 0 ≤ r2 − r1 ≤ 49
  • 0 ≤ c2 − c1 ≤ 4