KatInterview

Rearrange Grid Cells into Alternating-Row Order via Adjacent Swaps

Arrays & HashingModel answer
HardModel answerArrays & Hashingmatrixgreedysimulation

Last updated

Output a sequence of orthogonal-neighbor swaps that transforms a permuted square grid into alternating-row sorted form.

You are given a square grid of size n × n containing each integer from 1 to n² exactly once. Your task is to rearrange the grid into alternating-row sorted order:

  • Row 0 contains values in increasing order from left to right
  • Row 1 contains values in increasing order from right to left
  • Row 2 goes left to right again
  • This pattern continues, alternating with each row

You may perform adjacent-cell swaps: exchange the contents of two cells that share an edge (up, down, left, or right). Diagonal neighbors cannot be swapped.

Write a function that returns any valid sequence of swaps achieving the target layout. Each swap is represented as a pair [a, b] of the two values being exchanged at the moment that swap occurs. Because values are unique, the pair identifies which two cells are involved. You do not need to minimize the number of swaps.

Input:

  • board: an n × n matrix, a permutation of 1..n²
  • Assume 1 ≤ n ≤ 20

Output:

  • A list of swaps [[val1, val2], ...] where each pair specifies two values that are orthogonally adjacent at the time of that operation
  • Return an empty list if the board is already in target order

Examples:

Input: [[2, 1], [3, 4]]
Target: [[1, 2], [4, 3]]
One valid output: [[2, 1], [4, 3]]

Input: [[1, 2, 3], [6, 5, 4], [7, 8, 9]]
Output: [] (already sorted)

Clarifications:

  • Multiple correct answers exist; any valid sequence is acceptable
  • Adjacency is checked at swap time, not based on initial positions
  • You may mutate the input board during your solution

Hints

Hint 1

Consider placing each value into its final position one at a time, starting from 1 and working upward.

Hint 2

To move a value toward its destination, swap it repeatedly with neighbors along a path—similar to bubble sort in two dimensions.

Hint 3

The target position for value k can be computed from its row and the alternating-direction pattern of that row.