Rearrange Grid Cells into Alternating-Row Order via Adjacent Swaps
Arrays & HashingModel answerLast 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: ann × nmatrix, a permutation of1..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.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The core idea is a greedy, position-by-position placement strategy: place value 1 into its target cell, then 2, then 3, and so on up to n². Once a value reaches its correct cell, we never disturb it again by only working on values that are still out of place.
Target Position Calculation
For a given value k (where 1 ≤ k ≤ n²):
- Determine which row it belongs to:
row = (k - 1) // n - Within that row, compute the column:
- If
rowis even, the row runs left-to-right:col = (k - 1) % n - If
rowis odd, the row runs right-to-left:col = n - 1 - ((k - 1) % n)
- If
Moving a Value to Its Target
To move value k from its current position (r_curr, c_curr) to its target (r_target, c_target):
- Vertical movement first: Repeatedly swap
kwith the neighbor above or below untilr_curr == r_target. - Horizontal movement: Then swap
kleft or right untilc_curr == c_target.
Each swap exchanges k with an adjacent cell. Because we process values in increasing order and only touch cells that will eventually hold larger values, we never accidentally move an already-placed value.
Correctness
- Legality: Every swap involves two values that are orthogonally adjacent at the moment of the operation.
- Termination: Each value is moved exactly once along a monotonic path (first vertically, then horizontally), so the algorithm completes in finite time.
- Correctness: After placing values
1throughk, those cells are locked in their final positions. Subsequent placements only affect cells meant for larger values, preserving earlier work.
Complexity
- Time: For each of
n²values, we perform at mostO(n)swaps (at mostn-1vertical plusn-1horizontal). Total: O(n³) swaps and O(n³) time. - Space: O(n²) to track current positions and store the output sequence.
The sequence length is not minimized, but the algorithm is straightforward to implement and verify.
Implementation
def snake_sort_swaps(board):
n = len(board)
if n == 0:
return []
# Build a map: value -> (row, col)
pos = {}
for r in range(n):
for c in range(n):
pos[board[r][c]] = (r, c)
def target_position(val):
"""Compute the target (row, col) for val."""
idx = val - 1
row = idx // n
col_in_row = idx % n
if row % 2 == 0:
# Even row: left to right
col = col_in_row
else:
# Odd row: right to left
col = n - 1 - col_in_row
return (row, col)
def swap_cells(r1, c1, r2, c2):
"""Swap two cells and update position map."""
val1, val2 = board[r1][c1], board[r2][c2]
board[r1][c1], board[r2][c2] = val2, val1
pos[val1], pos[val2] = (r2, c2), (r1, c1)
return [val1, val2]
swaps = []
for val in range(1, n * n + 1):
r_curr, c_curr = pos[val]
r_target, c_target = target_position(val)
# Move vertically
while r_curr < r_target:
swaps.append(swap_cells(r_curr, c_curr, r_curr + 1, c_curr))
r_curr += 1
while r_curr > r_target:
swaps.append(swap_cells(r_curr, c_curr, r_curr - 1, c_curr))
r_curr -= 1
# Move horizontally
while c_curr < c_target:
swaps.append(swap_cells(r_curr, c_curr, r_curr, c_curr + 1))
c_curr += 1
while c_curr > c_target:
swaps.append(swap_cells(r_curr, c_curr, r_curr, c_curr - 1))
c_curr -= 1
return swaps
Testing and Validation
# Test 1: 2×2 example
board = [[2, 1], [3, 4]]
result = snake_sort_swaps(board)
# board is now [[1, 2], [4, 3]]
assert board == [[1, 2], [4, 3]]
# Test 2: Already sorted
board = [[1, 2, 3], [6, 5, 4], [7, 8, 9]]
result = snake_sort_swaps(board)
assert result == []
# Test 3: 3×3 fully scrambled
board = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
result = snake_sort_swaps(board)
assert board == [[1, 2, 3], [6, 5, 4], [7, 8, 9]]
Common Mistakes
- Swapping by initial coordinates instead of current values: The swap pairs must reflect the values at the moment of the swap, not their starting positions.
- Breaking already-placed values: Processing out of order or using a non-monotonic path can disturb earlier placements.
- Off-by-one errors in target calculation: Carefully handle zero-indexing and the alternating-direction formula.
- Ignoring adjacency checks in testing: Validate that each returned pair is orthogonally adjacent when that swap executes.
Follow-Up: Reducing Swap Count
A shortest-path approach treats the problem as a permutation puzzle and applies BFS or A* with a heuristic (e.g., Manhattan distance sum). This is computationally expensive for larger n. In practice, the greedy method is simple, correct, and produces a reasonable—though not optimal—swap count.