Minimum Swaps to Group Ones in a Square
Problem statement
Given a square binary matrix grid, move all its ones into one contiguous, axis-aligned square using as few swaps as possible. There are exactly k * k ones for some positive integer k, so the destination square has side length k.
For this exercise, one swap exchanges the contents of any two cells; the cells need not be adjacent. Return the minimum number of swaps. The input always permits a k x k square within the matrix.
Function
minimumSquareGroupingSwaps(grid: int[][]) → intExamples
Example 1
grid = [[1,0,0],[1,0,1],[0,1,0]]return = 2The source example has four ones. The top-left 2 by 2 square already contains two, so two swaps bring the other ones inside.
Example 2
grid = [[1,1,0],[1,1,0],[0,0,0]]return = 0All four ones already fill a contiguous square.
Example 3
grid = [[1,0,1],[0,0,0],[1,0,1]]return = 3Every 2 by 2 square contains only one of the four corner ones.
Constraints
1 <= grid.length <= 100; every row has the same length as the number of rows.- Every cell is
0or1. - The number of ones is a positive perfect square
k * k, with1 <= k <= grid.length.