#P1274. Magic 4×4 Grid Puzzle

    ID: 14561 Type: Default 1000ms 256MiB

Magic 4×4 Grid Puzzle

Magic 4×4 Grid Puzzle

Fill a 4×4 grid with the numbers 1 through 16 (each used exactly once) so that every one of the following groups of 4 cells sums to \(34\):

  • The four corner cells: \(A_{1,1}+A_{1,4}+A_{4,1}+A_{4,4}=34\).
  • Every 2×2 block at the corners. For example, the top‐left block: \(A_{1,1}+A_{1,2}+A_{2,1}+A_{2,2}=34\).
  • The central 2×2 block: \(A_{2,2}+A_{2,3}+A_{3,2}+A_{3,3}=34\).
  • Every row: \(A_{i,1}+A_{i,2}+A_{i,3}+A_{i,4}=34\) for \(i=1,\dots,4\).
  • Every column: \(A_{1,j}+A_{2,j}+A_{3,j}+A_{4,j}=34\) for \(j=1,\dots,4\).
  • Both main diagonals: \(A_{1,1}+A_{2,2}+A_{3,3}+A_{4,4}=34\) and \(A_{1,4}+A_{2,3}+A_{3,2}+A_{4,1}=34\).

In addition, the number \(1\) is fixed in a specified cell. It turns out that (up to rotations and reflections) there is exactly one solution – the classical Dürer magic square – that meets all these conditions. Your task is to output a valid arrangement where the given cell holds the number \(1\).

inputFormat

The input consists of two space‐separated integers \(r\) and \(c\) (1-indexed) representing the row and column where the number \(1\) is fixed. It is guaranteed that the fixed position is one of the four corners (i.e. one of \((1,1), (1,4), (4,1), (4,4)\)) so that a valid solution exists.

outputFormat

If a valid arrangement exists, output the 4×4 grid. Each of the 4 lines should contain 4 space‐separated integers representing one row of the grid.

sample

4 4
16 3 2 13

5 10 11 8 9 6 7 12 4 15 14 1

</p>