All problems

Problem 998

Spiral Matrix III

Medium · 20 pts · Matrix, Simulation

Problem

You start at cell (R0, C0) of an R × C grid, facing east, and walk in a clockwise spiral: 1 step east, 1 south, 2 west, 2 north, 3 east, 3 south, and so on, with the step length growing by one after every two turns. The walk may leave the grid and come back. List the grid cells in the order you first visit them, until every cell has been visited. Print each cell as row and column.

Input

A single line with R, C, R0 and C0.

Output

Print R × C lines, each with the row and column of the next visited cell.

Constraints

1 <= R, C <= 100; 0 <= R0 < R; 0 <= C0 < C

Example input

1 4 0 0

Example output

0 0
0 1
0 2
0 3

Explanation

In a 1 × 4 grid starting at (0, 0), the spiral visits (0, 0), then (0, 1) going east, wanders outside the grid, and later comes back east through (0, 2) and (0, 3).

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Max Increase to Keep City Skyline Next: Number of Submatrices That Sum to Target