1536. Minimum Swaps to Arrange a Binary Grid
Approach
Precompute suffix zeros per row; for each diagonal requirement greedily find the nearest valid row and bubble it up.
Key Techniques
Array problems involve manipulating elements stored in a contiguous block of memory. Key techniques include two-pointer traversal, prefix sums, sliding windows, and in-place partitioning. In C#, arrays are zero-indexed and fixed in size — use List<T> when you need dynamic resizing.
Greedy algorithms make locally optimal choices at each step, hoping to reach a global optimum. Greedy works when a problem has the "greedy choice property" and "optimal substructure". Common applications: interval scheduling, activity selection, Huffman coding, and jump game.
Matrix problems often involve BFS/DFS flood fill, dynamic programming on 2D grids, or spiral/diagonal traversal. For row × column DP, break it into 1D sub-problems column by column. Common pitfalls: boundary checks and modifying the input matrix in-place.
// Approach: Precompute suffix zeros per row; for each diagonal requirement greedily find the nearest valid row and bubble it up.
// Time: O(n²) Space: O(n)
public class Solution
{
public int MinSwaps(int[][] grid)
{
int n = grid.Length;
int ans = 0;
// suffixZeros[i] := the number of suffix zeros in the i-th row
int[] suffixZeros = new int[n];
for (int i = 0; i < grid.Length; ++i)
suffixZeros[i] = GetSuffixZeroCount(grid[i]);
for (int i = 0; i < n; ++i)
{
int neededZeros = n - 1 - i;
// Get the first row with suffix zeros >= `neededZeros` in suffixZeros[i:..n).
int j = GetFirstRowWithEnoughZeros(suffixZeros, i, neededZeros);
if (j == -1)
return -1;
// Move the rows[j] to the rows[i].
for (int k = j; k > i; --k)
suffixZeros[k] = suffixZeros[k - 1];
ans += j - i;
}
return ans;
}
private int GetSuffixZeroCount(int[] row)
{
for (int i = row.Length - 1; i >= 0; --i)
{
if (row[i] == 1)
return row.Length - i - 1;
}
return row.Length;
}
// Returns first row that has suffix zeros >= `neededZeros` in suffixZeros[i:..n).
private int GetFirstRowWithEnoughZeros(int[] suffixZeros, int i, int neededZeros)
{
for (int j = i; j < suffixZeros.Length; ++j)
{
if (suffixZeros[j] >= neededZeros)
return j;
}
return -1;
}
}