Leetcode 1536: Minimum Swaps to Arrange a Binary Grid

grid47
grid47
Exploring patterns and algorithms
Jun 6, 2024 7 min read

You are given an n x n binary grid, and in one move, you can swap any two adjacent rows. The grid is valid if all the cells above the main diagonal are zeros. Your task is to return the minimum number of swaps needed to make the grid valid, or -1 if it’s not possible.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer grid of size n x n, where each element is either 0 or 1.
Example: grid = [[0, 1, 1], [1, 0, 1], [1, 0, 0]]
Constraints:
• n == grid.length == grid[i].length
• 1 <= n <= 200
• grid[i][j] is either 0 or 1
Output: Return the minimum number of swaps required to make the grid valid, or -1 if it's not possible.
Example: For grid = [[0, 1, 1], [1, 0, 1], [1, 0, 0]], the output is 2.
Constraints:
• The output is an integer indicating the number of swaps required or -1 if the grid cannot be made valid.
Goal: The goal is to transform the grid such that all the cells above the main diagonal are zeros by performing a minimum number of adjacent row swaps.
Steps:
• For each row, count the number of trailing zeros.
• For each row, try to find a valid position that can be swapped to fulfill the condition of zeros above the main diagonal.
• Simulate the row swaps and track how many steps it takes to achieve a valid grid.
Goal: Ensure that the solution can handle the constraints efficiently.
Steps:
• The grid will always have n x n elements with 0 or 1 values.
• n can be as large as 200, so an efficient solution is necessary.
Assumptions:
• The grid contains distinct rows in terms of binary values.
• It's guaranteed that a valid grid is achievable for some test cases, and for others, it's not possible.
Input: grid = [[0, 1, 1], [1, 0, 1], [1, 0, 0]]
Explanation: By swapping rows 0 and 2, followed by swapping rows 1 and 2, we can make the grid valid with 2 moves.

Input: grid = [[0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0], [0, 1, 1, 0]]
Explanation: Since all the rows are the same, no valid transformation is possible, and the output is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus