We’re preparing your current view and syncing the latest data.
Minimum number of swaps to bring zeros to front in binary matrix rows
gfgYou are given an n x n binary grid grid. In one operation, you can swap any two adjacent rows of the grid. A grid is said to be valid if all the cells above the main diagonal are 0s (that is, for every i and j where i < j, grid[i][j] == 0).
Return the minimum number of swaps needed to make the grid valid. If it's not possible to make the grid valid, return -1.
Example: Input: grid = [[0,0,1],[1,1,0],[1,0,0]] Output: 3
An integer n representing the size of the grid, followed by a 2D array grid of size n x n of binary integers (0 or 1).
An integer representing the minimum number of swaps needed to make the grid valid, or -1 if impossible.
1 <= n <= 200 grid[i][j] is either 0 or 1.
Example 1
Input
[[0,0,1],[1,1,0],[1,0,0]]
Output
3
Explanation
To make the grid valid, minimum 3 adjacent row swaps are needed.